mkleehammer / pyodbc

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

Cannot load data to sql database #1155

Closed Edimo05 closed 1 year ago

Edimo05 commented 1 year ago

Please first make sure you have looked at:

Environment

To diagnose, we usually need to know the following, including version numbers. On Windows, be sure to specify 32-bit Python or 64-bit:

ERROR: (pyodbc.OperationalError) ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]Named Pipes Provider: Could not open a connection to SQL Server [53]. (53) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 17 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (53)')

Code: user = 'Periquito' password = 'PinPinPinPan' server = 'internal-tools-db.devfacebook.com' dbname = 'AdManagementTool' driver='{ODBC Driver 17 for SQL Server}'

df.to_sql(table, f"mssql+pyodbc://ERRSTSDBP2/{user}:{password}@{server}/{dbname}?driver=ODBC+Driver+17+for+SQL+Server", if_exists='append', index=False)

I already stablished a connection with the server in other codes, using pyodbc, not sure why is not working just in this one.

v-chojas commented 1 year ago

It doesn't look like you're using pyODBC directly, could you try connecting directly?

Edimo05 commented 1 year ago

@gordthompson , I got the same error: Expected URI to be a string, got <class 'sqlalchemy.engine.base.Engine'>. @v-chojas if I connect directly, the same error as above appears.

gordthompson commented 1 year ago

Leave pandas' .to_sql() out of the mix for now. Does this code work?

import pyodbc

user = 'Periquito'
password = 'PinPinPinPan'
server = 'internal-tools-db.devfacebook.com'
dbname = 'AdManagementTool'
driver='{ODBC Driver 17 for SQL Server}'

connection_string = (
    f"Driver={driver};"
    f"Server={server};"
    f"Database={dbname};"
    f"UID={user};"
    f"PWD={password};"
)
cnxn = pyodbc.connect(connection_string)
crsr = cnxn.cursor()
result = crsr.execute("SELECT 'Connected!' AS foo").fetchval()
print(result)

If not, then please post the complete stack trace.