写入 MySQL 时 to_sql() 查询 sqlite_master 表时出错 [英] to_sql() error querying sqlite_master table when writing to MySQL
问题描述
我有一个关于如何将数据框保存到本地 mysql 的问题.
I have a question about how to save a dataframe to my local mysql.
import MySQLdb
import pandas as pd
conn=MySQLdb.connect(host="localhost",user='root',passwd="matt123",db="ada")
df=pd.DataFrame(['A','B'],columns=['new_tablecol'])
df.to_sql(name='new_table',con=conn,if_exists='append')
输入此代码后,它说
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
我对此感到困惑.我可以查询和创建表.但我无法保存此数据框.
I am confused about this.I can query and create table . but I can't save this dataframe.
推荐答案
不再支持您的方式.
con : SQLAlchemy 引擎或 DBAPI2 连接(传统模式)
con : SQLAlchemy engine or DBAPI2 connection (legacy mode)
使用 SQLAlchemy 可以使用它支持的任何数据库图书馆.如果是 DBAPI2 对象,则仅支持 sqlite3.
Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, only sqlite3 is supported.
风味:‘sqlite’,默认无
flavor : ‘sqlite’, default None
自 0.19.0 版起已弃用:‘sqlite’是唯一受支持的选项如果不使用 SQLAlchemy.
Deprecated since version 0.19.0: ‘sqlite’ is the only supported option if SQLAlchemy is not used.
试试这个?
from sqlalchemy import create_engine
import pandas as pd
engine = create_engine("mysql://root:matt123@localhost/ada")
con = engine.connect()
df = pd.DataFrame(['A','B'],columns=['new_tablecol'])
df.to_sql(name='new_table',con=con,if_exists='append')
con.close()
语法是:
engine = create_engine("mysql://USER:PASSWORD@HOST/DATABASE")
有关 sqlalchemy
的更多信息可以在这里找到
More information about sqlalchemy
can be found here
这篇关于写入 MySQL 时 to_sql() 查询 sqlite_master 表时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!