【发布时间】:2016-04-16 12:01:44
【问题描述】:
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)
错误出现在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
如果有人可以建议一些解决方法,那将是非常有帮助的。我不想用 cursor.execute() 尝试这个
【问题讨论】:
-
不再支持将 MySQL 与原始连接一起使用(如果您提供
flavor='mysql'到to_sql,它应该仍然有效(默认为 'sqlite',如您在错误回溯中看到的那样),但它已被弃用)。您可以尝试制作一个 SQLAlchemy 引擎并将其传递给to_sql而不是con吗?见pandas.pydata.org/pandas-docs/stable/io.html#io-sql -
不知道有没有人解决这个问题。我创建了 SQLAlchemy 引擎并将其传递给
to_sql,但没有运气...
标签: python sql pandas formatting mysql-python