【问题标题】:to_sql() error querying sqlite_master table when writing to MySQL写入 MySQL 时查询 sqlite_master 表时出现 to_sql() 错误
【发布时间】:2017-08-25 10:57:05
【问题描述】:

我有一个关于如何将数据框保存到本地 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

我对此感到困惑。我可以查询和创建表。但我无法保存此数据框。

【问题讨论】:

    标签: pandas mysql-python pandas-to-sql


    【解决方案1】:

    不再支持您的方式。

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

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

    风格:'sqlite',默认无

    自 0.19.0 版起已弃用:“sqlite”是唯一受支持的选项 如果不使用 SQLAlchemy。

    pandas.DataFrame.to_sql

    试试这个?

    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的信息可以找到here

    【讨论】:

      猜你喜欢
      • 2021-11-14
      • 2021-01-25
      • 2020-11-03
      • 2018-05-14
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      • 2018-09-27
      相关资源
      最近更新 更多