Pandas DataFrame.to_sql()错误-字符串格式化期间未转换所有参数

Yog*_*dav 5 python sql formatting mysql-python pandas

Python版本-2.7.6

熊猫版-0.17.1

MySQLdb版本-1.2.5

DataFrame.to_sql()pandas.io.sql.DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': not all arguments converted during string formatting

Python代码段

con = MySQLdb.connect('localhost', 'root', '', 'product_feed')
cur = con.cursor()
cur.execute("SELECT VERSION()")
connection_result = cur.fetchall()
print connection_result[0][0]     #It prints 5.5.44-0ubuntu0.14.04.1

table_column = ['A', 'B', 'C']
created_data = numpy.array([numpy.arange(10)]*3).T
df = pandas.DataFrame(data=created_data ,columns=table_column)
df.to_sql('test_table', con)
Run Code Online (Sandbox Code Playgroud)

该错误来自df.to_sql('test_table', con)行的执行。

错误详情

  File "/home/yogi/yogi/mlPython/product_feed/etl_pf/process_data.py", line 298, in render_df
    df.to_sql('test_table', con)
  File "/home/yogi/yogi/mlenv/local/lib/python2.7/site-packages/pandas/core/generic.py", line 1003, in to_sql
    dtype=dtype)
  File "/home/yogi/yogi/mlenv/local/lib/python2.7/site-packages/pandas/io/sql.py", line 569, in to_sql
    chunksize=chunksize, dtype=dtype)
  File "/home/yogi/yogi/mlenv/local/lib/python2.7/site-packages/pandas/io/sql.py", line 1640, in to_sql
    table.create()
  File "/home/yogi/yogi/mlenv/local/lib/python2.7/site-packages/pandas/io/sql.py", line 685, in create
    if self.exists():
  File "/home/yogi/yogi/mlenv/local/lib/python2.7/site-packages/pandas/io/sql.py", line 673, in exists
    return self.pd_sql.has_table(self.name, self.schema)
  File "/home/yogi/yogi/mlenv/local/lib/python2.7/site-packages/pandas/io/sql.py", line 1653, in has_table
    return len(self.execute(query, [name,]).fetchall()) > 0
  File "/home/yogi/yogi/mlenv/local/lib/python2.7/site-packages/pandas/io/sql.py", line 1554, in execute
    raise_with_traceback(ex)
  File "/home/yogi/yogi/mlenv/local/lib/python2.7/site-packages/pandas/io/sql.py", line 1543, in execute
    cur.execute(*args)
  File "/home/yogi/yogi/mlenv/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 187, in execute
    query = query % tuple([db.literal(item) for item in args])
pandas.io.sql.DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': not all arguments converted during string formatting
Run Code Online (Sandbox Code Playgroud)

我检查了熊猫0.17.1是否主要使用.format(),因此不会由于%格式化而出现此错误。

如果有人可以建议一些解决方法,那将是很大的帮助。我不想尝试cursor.execute()

小智 1

参数:

\n\n

con :SQLAlchemy 引擎或 DBAPI2 连接(传统模式)

\n\n

使用 SQLAlchemy 可以使用该库支持的任何数据库。如果是 DBAPI2 对象,则仅支持 sqlite3。

\n\n

风味:\xe2\x80\x98sqlite\xe2\x80\x99,默认无

\n\n

自版本 0.19.0 起已弃用:如果不使用 SQLAlchemy,则 \xe2\x80\x98sqlite\xe2\x80\x99 是唯一受支持的选项。

\n\n

如果你使用 SQLAlchemy 而不是 MySQLdb 就可以了。

\n