简体   繁体   English

使用to_sql函数时出错

[英]Error while using the to_sql function

I am using the following code to extract data from SQL into a Data Frame and it works fine. 我正在使用以下代码将数据从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

But when I add this line 但是当我添加这一行

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

to send data back to the Server I get an error that says 将数据发送回服务器我得到一个错误,说

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)")

I have tried a variety of solutions and just can't get it to work. 我尝试了多种解决方案,但无法使其正常工作。

I believe the issue is in your "con = cnxn" statement. 我相信问题出在您的“ con = cnxn”声明中。 Try this: 尝试这个:

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用python中的to_sql函数将数据帧插入Sql-server DB时出错 - Error while insert dataframe to Sql-server DB using to_sql function in python UnicodeEncodeError: 在 python 中使用 to_sql 时 - UnicodeEncodeError: while using to_sql in python 尝试使用to_sql函数插入时,数据库引擎无法连接到sql-server实例 - Database engine fails to connect to a sql-server instance while trying to insert using to_sql function 使用.to_sql()上传DataFrame时出现“SELECT name FROM sqlite_master”错误 - "SELECT name FROM sqlite_master" error while uploading DataFrame using .to_sql() 使用to_sql将pandas df写入mysql时抛出错误 - Error thrown when using to_sql to write pandas df to mysql 在 MS Access 中使用 to_sql(..., method='multi') 时出错 - Error using to_sql(… , method='multi') with MS Access 使用 to_sql 将 pandas dataframe 导出到访问表中生成错误 - exporting pandas dataframe into a access table using to_sql generate error 使用to_sql将熊猫数据框中的数据导入SQL数据库时,PC挂起 - PC hangs while importing data from pandas dataframe into SQL database using to_sql 如何加快Pandas .to_sql功能? - How to speed up Pandas .to_sql function? AttributeError:“ generator”对象没有属性“ to_sql”时,使用生成器创建datframe - AttributeError: 'generator' object has no attribute 'to_sql' While creating datframe using generator
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM