【问题标题】:Error while using the to_sql function使用 to_sql 函数时出错
【发布时间】:2018-04-13 22:29:03
【问题描述】:

我正在使用以下代码将数据从 SQL 提取到数据框中,并且工作正常。

import pyodbc 
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=DESKTOP-5422GFU;"
                      "Database=Python_Data;"
                      "Trusted_Connection=yes;"
                      "uid=User;pwd=password")

df = pd.read_sql_query('select * from Persons', cnxn)

df

但是当我添加这一行时

df.to_sql('test', schema = 'public', con = cnxn, index = False, 
if_exists = 'replace')

要将数据发送回服务器,我收到一条错误消息

DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': ('42S02', "[42S02] [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid object name 'sqlite_master'. (208) (SQLExecDirectW); [42S02] [Microsoft][SQL Server Native Client 11.0][SQL Server]Statement(s) could not be prepared. (8180)")

我尝试了多种解决方案,但都无法正常工作。

【问题讨论】:

标签: python sql-server pandas-to-sql


【解决方案1】:

我相信问题出在您的“con = cnxn”声明中。试试这个:

import pandas as pd    
import sqlalchemy
from sqlalchemy import create_engine

OBDC_cnxn='Python_Data_ODBC' #this will be the name of the ODBC connection to this database in your ODBC manager.
engine = create_engine('mssql+pyodbc://'+ODBC_cnxn)

df.to_sql('test', schema = 'public', con = engine, index = False, 
if_exists = 'replace')

【讨论】:

    猜你喜欢
    • 2018-01-23
    • 2021-11-25
    • 2021-01-25
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多