1
我想使用熊貓函數to_sql將數據框寫入MariaDB數據庫。裏面PyCharm我的Python代碼如下:pandas dataframe to mariadb數據庫to_sql和sqlalchemy
import pandas as pd
import mysql.connector
from sqlalchemy import create_engine
myd = pd.read_csv('/[path]/[filename].csv')
engine = create_engine('mysql+mysqlconnector://[user]:[pw]@127.0.0.1/[dbname]')
myd.to_sql(name='[tablename]', con=engine, if_exists='replace', index=False)
執行在控制檯中我得到以下錯誤的最後一行時:
Error on sql SELECT name FROM sqlite_master WHERE type='table' AND name='[tablename]';
Traceback (most recent call last):
File "/usr/lib/python3.4/code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "/usr/lib/python3/dist-packages/pandas/core/frame.py", line 1261, in to_sql
self, name, con, flavor=flavor, if_exists=if_exists, **kwargs)
File "/usr/lib/python3/dist-packages/pandas/io/sql.py", line 207, in write_frame
exists = table_exists(name, con, flavor)
File "/usr/lib/python3/dist-packages/pandas/io/sql.py", line 275, in table_exists
return len(tquery(query, con)) > 0
File "/usr/lib/python3/dist-packages/pandas/io/sql.py", line 90, in tquery
cur = execute(sql, con, cur=cur)
File "/usr/lib/python3/dist-packages/pandas/io/sql.py", line 44, in execute
cur = con.cursor()
AttributeError: 'Engine' object has no attribute 'cursor'
Here有人在一個點有同樣的錯誤。但是,在某人解決問題之前,它已經消失了。你知道什麼是錯的嗎?
通常情況下,如果您使用的是舊熊貓版本(在支持sqlalchemy引擎之前),則可能會出現此錯誤。你能顯示「pd .__ version__」的輸出嗎? – joris
這給出0.13.1 - 我需要更新熊貓,對吧? – nluckn
的確,最低版本爲0.14。否則,你可以傳遞原始連接(''engine.raw_connection()'')和'flavor ='mysql''(但在新版本中不再支持)。 – joris