我目前在 JSON 配置文件中的 SQLite 内容:
"db": "sqlite:///\\\\F\\Evaluations\\data\\abc.db"
我想要的是连接到 SQL Server 中的数据库。我该怎么做?
db
在不同的 python 文件中在管道中多次使用,如下所示:
...
self.db = settings['db']
...
engine = sa.create_engine( self.db, echo=False)
conn = engine.connect()
答案 0 :(得分:0)
首先,尝试使用以下命令安装pyodbc:
pip install pyodbc
然后,您可以简单地将 MS SQL URI 连接添加到 JSON 配置文件中,如下所示:
"db_mssql":"mssql+pyodbc://username:password@host:port/database"
然后,在你的 python 脚本中:
self.db = settings['db_mssql']
engine = sa.create_engine( self.db, echo=False)
conn = engine.connect()
答案 1 :(得分:0)
看起来您是通过 sqlalchemy 连接的。 SQL 服务器的连接字符串需要包含更多信息,例如:
最好先在不同的脚本中进行测试。
import sqlalchemy as db
import pyodbc # you may need to install pyodbc (or use a different supported driver)
server_name = 'localhost'
database_name = 'AdventureWorks2019'
# directly specify your driver
driver = 'ODBC Driver 17 for SQL Server'
# or use pyodbc to find it
# driver = [x for x in pyodbc.drivers() if x.endswith(' for SQL Server')]
# driver = driver[0]
# specifying a username/password
engine = db.create_engine('mssql+pyodbc://USERNAME:PASSWORD@'+server_name+'/'+database_name+'?driver='+driver)
# or using a trusted connection
# sqlalchemy will add "trusted_connection=yes" if username/password isn't specified
engine = db.create_engine('mssql+pyodbc://@'+server_name+'/'+database_name+'?driver='+driver)
那么您的 JSON 配置最终将类似于:
"db": "mssql+pyodbc://USERNAME:PASSWORD@localhost/AdventureWorks2019?driver=ODBC Driver 17 for SQL Server"
OR
"db": "mssql+pyodbc://@localhost/AdventureWorks2019?driver=ODBC Driver 17 for SQL Server"
旁注,如果您发现自己需要,还有一个额外的参数可以加快插入到 SQL 服务器的速度。
db.create_engine('mssql+pyodbc://USERNAME:PASSWORD@'+server_name+'/'+database_name+'?driver='+driver, fast_executemany=True)
参考链接:
https://docs.sqlalchemy.org/en/14/core/engines.html https://docs.sqlalchemy.org/en/14/dialects/mssql.html