当我尝试将PANDAS DataFrame写回SQL数据库时,我会遇到错误

发布于 2025-02-05 21:11:18 字数 802 浏览 2 评论 0原文

我正在尝试从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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

猥︴琐丶欲为 2025-02-12 21:11:18

docs 代码> dataframe.to_sql()有望为 sqlalchemy.engine。(引擎或连接)或sqlite3.connection

con sqlalchemy.engine。(发动机或连接)或sqlite3.connection
使用SQLalchemy可以使用该库支持的任何DB。为sqlite3.connection对象提供了遗产支持。
用户负责发动机处置和连接的连接
sqlalchemy可连接参见在这里。。

As per the docs, the second parameter of DataFrame.to_sql() is expected to be sqlalchemy.engine.(Engine or Connection) or sqlite3.Connection

con sqlalchemy.engine.(Engine or Connection) or sqlite3.Connection
Using SQLAlchemy makes it possible to use any DB supported by that library. Legacy support is provided for sqlite3.Connection objects.
The user is responsible for engine disposal and connection closure for
the SQLAlchemy connectable See here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文