2017-07-26 92 views
2

在试图写一个pandas“据帧到sql-server,我得到这个错误:to_sql大熊猫数据帧到SQL服务器错误:DatabaseError

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); [42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Statement(s) could not be prepared. (8180)")

看来pandas正在考虑sqlite,而不是真实的数据库。

它不是一个连接问题,因为我可以从sql-server使用pandas.read_sql 连接相同的连接读取已使用

​​

这不是一个数据库的权限问题,或者因为我可以通过线写线设置使用相同的连接参数:

cursor = conn.cursor() 
cursor.execute('insert into test values (1, 'test', 10)') 
conn.commit() 

我可以只写一个循环由线到instert线,但我想知道为什么to_sql是不是w ^为我而言,我担心它不会那么高效。

环境: Python:2.7 Pandas:0.20.1 sqlalchemy:1.1.12

在此先感谢。

可运行例如

import pandas as pd 
from sqlalchemy import create_engine 
import urllib 

params = urllib.quote_plus("DRIVER={SQL Server Native Client 11.0};SERVER= 
<servername>;DATABASE=<databasename>;UID=<username>;PWD=<password>") 
engine = create_engine("mssql+pyodbc:///?odbc_connect=%s" % params) 

test = pd.DataFrame({'col1':1, 'col2':'test', 'col3':10}, index=[0]) 

test.to_sql("dbo.test", con=engine, if_exists="append", index=False) 
+0

你为什么想查询一个叫表'使用SQL Server sqlite_master'?无论你,我,还是我们两个都在这里失去了一些东西。 –

+0

你是怎么调用'to_sql'的?你是否将SQLAlchemy引擎作为[第二个参数](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html)传递? – unutbu

+0

嘿!不,我不是......我只是运行'df.to_sql(“dbo.test”,con = conn,if_exists =“append”)',熊猫自动搜索sqlite_master;我不知道为什么!哪里'conn = engine.connect()。connection' – AlexSB

回答

1

根据该to_sql doc,所述con参数或者是一个SQLAchemy发动机或遗留DBAPI2连接(sqlite3的)。由于您传递连接对象而不是SQLAlchemy引擎对象作为参数,因此pandas推断您正在传递DBAPI2连接或SQLite3连接,因为它是唯一支持的连接。要解决这个问题,只需要:

myeng = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect=%s" % params) 

# Code to create your df 
... 

# Now write to DB 
df.to_sql('table', myeng, index=False) 
+0

感谢您的回答。事实上,这是我尝试的第一件事,但我得到了以下错误:'AttributeError:'Engine'对象没有属性'cursor''。我将不胜感激任何解决方法。 – AlexSB

+0

嗯,试一下'conn = myeng.connect()',然后将它作为连接对象传递呢?我没有任何麻烦,将'myeng'作为参数传递给我,但是我使用'SQL Server的ODBC驱动程序13'作为我的ODBC驱动程序,所以它可能是驱动程序之间的细微差别。 –

+0

同样的结果...我也尝试过'engine.raw_connection()',我在另一篇文章中读到并得到了相同的结果。另外,我尝试将驱动程序更改为'[SQL Server]'和[ODBC驱动程序11 for SQL Server]',但没有任何运气...... – AlexSB

0

所以我遇到了同样的事情。我试图查看代码,无法弄清楚它为什么不能正常工作,但它看起来像卡住了这个电话。

pd.io.sql._is_sqlalchemy_connectable(engine) 

我发现,如果我跑这首返回true,但只要我跑df.to_sql后,运行它()返回False。现在我正在运行它,然后执行df.to_sql(),它实际上可以工作。

希望这会有所帮助。

0

试试这个。 好连接MS SQL服务器(SQL身份验证)和更新数据

from sqlalchemy import create_engine 
params = urllib.parse.quote_plus(
'DRIVER={ODBC Driver 13 for SQL Server};'+ 
'SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password) 

engine = create_engine("mssql+pyodbc:///?odbc_connect=%s" % params) 

#df: pandas.dataframe; mTableName:table name in MS SQL 
#warning: discard old table if exists 
df.to_sql(mTableName, con=engine, if_exists='replace', index=False)