问题描述
我正在尝试使用 sqlalchemy
从 Linux 连接到 SQL Server.此页面显示基于 DSN 的连接如下.
I am trying to connect to a SQL Server from Linux using sqlalchemy
. This page shows DSN-based connection as below.
engine = create_engine("mssql+pyodbc://scott:tiger@some_dsn")
有没有办法使用 DSN 指定数据库名称?我知道我们可以在 odbc.ini
或 SQL 查询中指定数据库名称,但我想知道我们是否也可以这样做.
Is there a way to specify a database name using DSN? I am aware that we can specify a database name either in odbc.ini
or a SQL query but I would like to know if we can also do something like this.
engine = create_engine("mssql+pyodbc://scott:tiger@some_dsn/databasename")
推荐答案
可以通过create_engine中的connect_args参数直接将参数传递给pyodbc.connect方法:
You can pass arguments directly to the pyodbc.connect method through the connect_args parameter in create_engine:
def my_create_engine(mydsn, mydatabase, **kwargs):
connection_string = 'mssql+pyodbc://@%s' % mydsn
cargs = {'database': mydatabase}
cargs.update(**kwargs)
e = sqla.create_engine(connection_string, connect_args=cargs)
return e
这也将使数据库能够通过多个事务/会话持久化.
This will also enable the database to be persisted through several transactions / sessions.
这篇关于sqlalchemy,用DSN指定数据库名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!