sqlalchemy, specify database name with DSN

情到浓时终转凉″ 提交于 2019-12-23 17:31:50

问题


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")

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")


回答1:


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.




回答2:


I just tried something like this and it seemed to work fine

engine = create_engine("mssql+pyodbc://scott:tiger@some_dsn")
engine.execute("USE databasename")

As a general rule we should be careful about changing the current catalog (a.k.a. "database") after establishing a connection because some technologies (e.g., JDBC Connection objects) keep track of the current catalog and can get confused if we directly call USE ... in T-SQL to change the current catalog. However, I'm not aware that pyodbc's Connection object does any such caching so this approach is probably okay.



来源:https://stackoverflow.com/questions/45468623/sqlalchemy-specify-database-name-with-dsn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!