[Python] Python how to load SQL Server table with sqlalchemy?

Discussão em 'Python' iniciado por Stack, Junho 18, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to load table using Python in most effective way, and learned that sqlalchemy / engine is the best tool for that. But I really struggle to make this construction work for SQL Server as my target, I did exactly like in here , played with all types of = "DRIVER={SQL Server Native Client 10.0} but still it doesn't work. For this tasks I don't have any other option like SSRS/linked servers/etc.. I created df with different method for easy testing. Layout of tables is identical, just different server/db. Below is my code:

    import pyodbc as pb
    import pandas as pd
    import sqlalchemy
    from sqlalchemy.engine import URL

    Source_connStr = 'Driver={SQL Server};Server=SQLXTBRR;Database=Base; Trusted_Connection=True;'
    Source_conn = pb.connect(Source_connStr)

    Target_connStr= 'Driver={SQL Server};Server=SQLXTBRR;Database=Custom; Trusted_Connection=True;'

    query = ("SELECT * FROM dbo.Cust_Clients")
    df = pd.read_sql(query,SQL_conn) ## <=== used to create df works OK
    print(df)

    connection_url = URL.create(
    "mssql+pyodbc", query={"odbc_connect": Target_connStr}
    )
    engine = sqlalchemy.create_engine(connection_url)

    df.to_sql('Cust_Clients', engine, if_exists='append', index=False) ##line 30 load into table

    #pd.read_sql('Cust_Clients',engine)


    And here is fragment of error messages, looks like it breaks on line 30. I tried to write and read with engine, same bad result. I assume first UserWarning: pandas only support SQLALchemy.. is not critical.

    C:\PythonScripts\LoadDB_V1.py:22: UserWarning: pandas only supports SQLAlchemy connectable (engine/connection) or database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 objects are not tested. Please consider using SQLAlchemy.
    df = pd.read_sql(query,SQL_conn)
    id first_name last_name ... deleted general_id consent_refused
    0 111111 John Walshes ... None 14785444 0

    [1 rows x 18 columns]
    mssql+pyodbc://?odbc_connect=Driver%3D%7BSQL+Server%7D%3BServer% SQLXTBRR%3BDatabase% Custom%3B+Trusted_Connection%3DTrue%3B
    Traceback (most recent call last):
    File "C:\PythonScripts\.venv\Lib\site-packages\sqlalchemy\engine\base.py", line 1963, in _exec_single_context
    self.dialect.do_execute(
    ~~~~~~~~~~~~~~~~~~~~~~~^
    ….
    pyodbc.Error: ('HY104', '[HY104] [Microsoft][ODBC SQL Server Driver]Invalid precision value (0) (SQLBindParameter)')

    The above exception was the direct cause of the following exception:

    Traceback (most recent call last):
    File "C:\PythonScripts\ LoadDB _V1.py", line 30, in <module>
    df.to_sql(Cust_Clients, engine, if_exists='append', index=False) ## load into table
    ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\PythonScripts\.venv\Lib\site-packages\pandas\util\_decorators.py", line 333, in wrapper
    return func(*args, **kwargs)

    Continue reading...

Compartilhe esta Página