簡體   English   中英

使用to_sql函數時出錯

[英]Error while using the to_sql function

我正在使用以下代碼將數據從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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM