2016-07-01 329 views
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有人在一个点有同样的错误。但是,在某人解决问题之前,它已经消失了。你知道什么是错的吗?

+0

通常情况下,如果您使用的是旧熊猫版本(在支持sqlalchemy引擎之前),则可能会出现此错误。你能显示“pd .__ version__”的输出吗? – joris

+0

这给出0.13.1 - 我需要更新熊猫,对吧? – nluckn

+0

的确,最低版本为0.14。否则,你可以传递原始连接(''engine.raw_connection()'')和'flavor ='mysql''(但在新版本中不再支持)。 – joris

回答

2

传递SQLAlchemy的引擎只支持从熊猫开始0.14.0

为了与旧版本的熊猫使用to_sql,你需要将原始连接(engine.raw_connection())和flavor='mysql'to_sql

myd.to_sql(name='[tablename]', con=engine.raw_connection(), flavor='mysql', if_exists='replace', index=False) 

但是,我建议升级您的熊猫版本(传递原始连接已弃用,并且不再支持新版熊猫版本,则只支持sqlalchemy引擎/连接)