I am not able to transfer this dataframe into a sql server database.
import pyodbc
import pandas as pd
# Connect to the database
conn = pyodbc.connect("Driver={SQL Server};"
"Server=servername;"
"Database=databasename;"
"Trusted_Connection=yes;")
# Create the table
cursor = conn.cursor()
cursor.execute("CREATE TABLE emails (email VARCHAR(255))")
# Write the DataFrame to the database
df.to_sql("emails", conn, if_exists="replace", index=False)
# Commit the transaction
conn.commit()
# Close the connection
conn.close()
The error it fives me is
ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'sqlite_master'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. (8180)")
The above exception was the direct cause of the following exception:
DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': ('42S02', "[42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'sqlite_master'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. (8180)")
What am I doing wrong?
Is pyodbc not correctly installed and if so how can i check it? Should I use another Driver as "ODBC Driver 17 for SQL Server" and if so how do I install it?
EDIT: I installed OCDB Driver 18 and added "TrustServerCertificate=YES;") to the connection bit. But now it just prints my first error.
('42S02', "[42S02] [Microsoft][ODBC Driver 18 for SQL Server][SQL Server]Invalid object name 'sqlite_master'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC Driver 18 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)")
The above exception was the direct cause of the following exception:
DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': ('42S02', "[42S02] [Microsoft][ODBC Driver 18 for SQL Server][SQL Server]Invalid object name 'sqlite_master'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC Driver 18 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)")