6

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

2
  • 1
    Have you tried just doing engine.execute("USE databasename") immediately after calling engine_create using the normal DSN syntax? Commented Aug 2, 2017 at 22:04
  • Oh wow this is great! I did not think of using SQL for this. Would you please turn this as an "answer" not "comment" so that I can choose this as a solution? Commented Aug 3, 2017 at 15:46

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

engine = create_engine("mssql+pyodbc://scott:tiger@some_dsn")
with engine.begin() as conn:
    conn.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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.