我正在使用以下代码通过 SQL alchemy 连接到 MySQL 数据库。from sqlalchemy import create_engineimport pandas as pdquery = "SELECT * FROM hello"engine = create_engine("mysql+pymysql://root:new_pass@localhost:3306/toronto_analytics")engine = engine.raw_connection()df = pd.DataFrame({"bob":"hello", "joe":14}, index=[0])df.to_sql('new_table', engine)连接到数据库后,我尝试使用数据框中的值创建一个新表。我连接到数据库正常,但随后df.to_sql抛出以下错误:---------------------------------------------------------------------------TypeError Traceback (most recent call last)/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pandas/io/sql.py in execute(self, *args, **kwargs) 1377 else:-> 1378 cur.execute(*args) 1379 return cur/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymysql/cursors.py in execute(self, query, args) 167 --> 168 query = self.mogrify(query, args) 169 /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymysql/cursors.py in mogrify(self, query, args) 146 if args is not None:--> 147 query = query % self._escape_args(args, conn) 148 TypeError: not all arguments converted during string formattingDuring handling of the above exception, another exception occurred:DatabaseError Traceback (most recent call last)<ipython-input-100-03413ab65608> in <module> 8 9 df = pd.DataFrame({"bob":"hedawo", "joe":14}, index=[0])---> 10 df.to_sql('newawa', engine)任何有关此错误的帮助将不胜感激。谢谢
1 回答
烙印99
TA贡献1829条经验 获得超13个赞
传递引擎本身,而不是 DB-API 连接(原始连接)。Pandas 仅支持 SQLite,如果直接使用 DB-API:
con:
sqlalchemy.engine.Engine
或sqlite3.Connection
使用 SQLAlchemy 可以使用该库支持的任何数据库。为sqlite3.Connection
对象提供了遗留支持。
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html
添加回答
举报
0/150
提交
取消