这是我的代码
import time
import urllib
import openpyxl
from sqlalchemy import create_engine, Column, Integer, String, text, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from astropy.table.tests.test_index import engine
from _sqlite3 import connect
connection_string = "DRIVER = {SQL Server};DATABASE =<dbname>; SERVER=<details>; UID =uid; PWD =pwd"
connection_string = urllib.parse.quote_plus(connection_string)
connection_string = "mssql+pyodbc:///?odbc_connect=%s" %connection_string
#engine = create_engine('mssql+pyodbc://UID:PWD@Servername:1433/DBname')
engine = create_engine(connection_string)
Base = declarative_base()
class Blc(Base):
__tablename__ = 'BLC_Database'
Row_no = Column(Integer, primary_key = True)
date = Column(String)
RES = Column(String)
BTTLCOLUMN = Column(String)
CS_HR = Column(Float)
def __repr__(self):
return "<BLC_Databse(Row_no = '%d', date='%s', RES = '%s', BTTLCOLUMN = '%s', CS_HR = '%0.2f')>" %(self.Row_no, self.date, self.RES, self.BTTLCOLUMN, self.CS_HR)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
print('Connection Successful')
我得到的错误如下:
sqlalchemy.exc.DBAPIError: (pyodbc.Error) ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
我正在尝试连接到SQL服务器。我试过不同的字符串选项。我也访问了这个link。我无法理解错误。
答案 0 :(得分:1)
这是我做的:
我去了ODBC管理并创建了一个新的DSN并使用它进行连接。
create_engine('mssql+pyodbc://UID:PWD@DSN')
你不需要提及驱动程序。如果一台服务器中有多个数据库,则可以在配置DSN时分配默认数据库。这对我有用。