sql-serverodbcpyodbcunixodbcazure-data-studio

I'm having trouble using the pyodbc package to connect with Microsoft SQL Server on my Mac


I have installed Docker Desktop to run an image which runs a container that contains the Microsoft SQL Server on my Mac, with Azure Data Studio as the GUI, as such: Current connection to Microsoft SQL Server on MacOS

I have been trying to use the pyodbc.connect() function to connect to the Microsoft SQL Server, so that I can extract data from many XML files and load it into the SQL Server. However, my code keeps failing at pyodbc.connect(), where it gives me the error:

conn = pyodbc.connect('DRIVER={/opt/homebrew/lib/libmsodbcsql.18.dylib};' pyodbc.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib '/opt/homebrew/lib/libmsodbcsql.18.dylib' : file not found (0) (SQLDriverConnect)")

I have installed homebrew, unixODBC and ODBC Driver 18 for SQL Server that was on the official Microsoft website. I tried searching many websites on what to do and all I read was that I need to be able to configure the odbc.ini file, but I am unsure exactly what I need to do to configure this file properly. Currently, my odbc.ini file is blank and my odbcinst.ini file has the following content:

odbcinst.ini file that I have

The current code that I have specifies the exact path directory to SQL Driver 18: my pyodbc.connect() code

Would appreciate any help regarding this,


Solution

  • conn = pyodbc.connect('DRIVER={/opt/homebrew/lib/libmsodbcsql.18.dylib};' pyodbc.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib '/opt/homebrew/lib/libmsodbcsql.18.dylib' : file not found (0) (SQLDriverConnect)")
    

    If ODBC Driver 18 for SQL Server is not installed properly, then you may get the above error. Follow the MS Document to install the Microsoft ODBC driver for SQL Server (macOS). Along with that, use the code below to connect to the SQL Server using pyodbc:

    import pyodbc
    
    conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};'
                           '<serverName>;'
                           'DATABASE=<databaseName>;'
                           'UID=<userName>;'
                           'PWD=<password>')
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM <tableName>")
    rows = cursor.fetchall()
    for row in rows:
        print(row)
    

    It will connect successfully, as shown below:

    enter image description here

    For more information, you can refer to this.