mkleehammer / pyodbc

Python ODBC bridge
https://github.com/mkleehammer/pyodbc/wiki
MIT No Attribution
2.93k stars 561 forks source link

Add support for changing the current catalog via Connection#set_attr #505

Open gordthompson opened 5 years ago

gordthompson commented 5 years ago

The Python DB API makes no mention of changing the current catalog. However, System.Data.Odbc in .NET has a Connection#ChangeDatabase method and

cnxn.ChangeDatabase("master")

results in

OdbcConsoleApp. 2414-2578   EXIT  SQLSetConnectAttrW  with return code 1 (SQL_SUCCESS_WITH_INFO)
        SQLHDBC             0x0623EB90
        SQLINTEGER                 109 <SQL_ATTR_CURRENT_CATALOG>
        SQLPOINTER          0x01FE57FC [      12] "master"
        SQLINTEGER                  12

        DIAG [01000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Changed database context to 'master'. (5701)

so in Python I tried

cnxn.set_attr(pyodbc.SQL_ATTR_CURRENT_CATALOG, "master")

but I got

Traceback (most recent call last):
  File "C:/Users/Gord/PycharmProjects/py3pyodbc_demo/main.py", line 96, in <module>
    cnxn.set_attr(pyodbc.SQL_ATTR_CURRENT_CATALOG, "master")
TypeError: an integer is required (got type str)

If set_attr could be modified to also accept a string value then we'd have a database-independent way of changing the current catalog.

v-chojas commented 5 years ago

This can already be done for pre-connect attributes: https://github.com/mkleehammer/pyodbc/pull/259 Perhaps some of the code there can be reused for doing it after connect.