当我尝试将PANDAS DataFrame写回SQL数据库时,我会遇到错误
我正在尝试从Northwind数据库中读取订单表,然后将其写回数据库,称为“ orders_new”。我有以下python代码:
import pyodbc
import pandas as pd
conn_str = (
r'DRIVER={SQL Server};'
r'SERVER=DESKTOP-A1DUCDS\SQLEXPRESS;'
r'DATABASE=Northwind;'
r'Trusted_Connection=yes;'
)
cnxn = pyodbc.connect(conn_str)
df = pd.read_sql_query('select * from Orders', cnxn)
print(df)
df.to_sql('Orders_New',con=cnxn,index=False)
但是,当我运行代码时,它会给我以下错误:
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)")
I am trying to read the Orders table from the Northwind database and then write it back to the database under a new table name called 'Orders_New'. I have the following Python code:
import pyodbc
import pandas as pd
conn_str = (
r'DRIVER={SQL Server};'
r'SERVER=DESKTOP-A1DUCDS\SQLEXPRESS;'
r'DATABASE=Northwind;'
r'Trusted_Connection=yes;'
)
cnxn = pyodbc.connect(conn_str)
df = pd.read_sql_query('select * from Orders', cnxn)
print(df)
df.to_sql('Orders_New',con=cnxn,index=False)
However, when I run the code it gives me the following error:
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)")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如 docs 代码> dataframe.to_sql()有望为 sqlalchemy.engine。(引擎或连接)或sqlite3.connection
As per the docs, the second parameter of
DataFrame.to_sql()
is expected to be sqlalchemy.engine.(Engine or Connection) or sqlite3.Connection