Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用to_sql函数时出错_Python_Sql Server_Pandas To Sql - Fatal编程技术网

Python 使用to_sql函数时出错

Python 使用to_sql函数时出错,python,sql-server,pandas-to-sql,Python,Sql Server,Pandas To Sql,我使用下面的代码将数据从SQL提取到数据帧中,效果很好 import pyodbc cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};" "Server=DESKTOP-5422GFU;" "Database=Python_Data;" "Trusted_Connection=yes;"

我使用下面的代码将数据从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)")

我已经尝试了多种解决方案,但都无法成功。

我相信问题在于您的“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')
可能重复的