0

我正在尝试从我的数据库中获取数据并尝试将其写入另一个表,但由于某种原因,dataframe.to_sql 会引发错误:

> engine = create_engine("mysql+pymysql://{user}:{pw}@localhost/{db}"
                       .format(user="root",
                               pw="dhanusha",
                               db="postmanassignment"),pool_pre_ping=True)
    mycursor.execute("CREATE TABLE IF NOT EXISTS agregated( name VARCHAR(255), 
                      no_of_products INT UNSIGNED, PRIMARY KEY (name))")
   mycursor.execute("SELECT name,COUNT(id)FROM products GROUP BY name limit 10")
   result = dict(mycursor.fetchall())    
   new=pd.DataFrame(result.items(),columns=['name', 'no_of_products'])
    print(new)
   new.to_sql('agregated', con = engine,dtype={"name": sqlalchemy.types.VARCHAR, "no_of-products": 
   sqlalchemy.types.INT},if_exists = 'append', chunksize = 10000,index= False)


**This gives an error:**

> OperationalError: (pymysql.err.OperationalError) (1054, "Unknown column 'no_of_products' in 'field list'")
4

1 回答 1

0

确保数据类型匹配。df.to_sql 中传递的表列类型和 dtype 应该匹配:

count_duplicate(): ```engine = create_engine("mysql+pymysql://{user}:{pw}@localhost/{db}" .format(user="root", pw="dhanusha", db=" postmanassignment"),pool_pre_ping=True)
mycursor.execute("CREATE TABLE IF NOT EXISTS agregated(name VARCHAR(255), no_of_products BIGINT UNSIGNED, PRIMARY KEY (name))") mycursor.execute("SELECT name,COUNT(id) FROM products GROUP BY name") result = dict(mycursor.fetchall()) new=pd.DataFrame(result.items(),columns=['name', 'no_of_products']) new.to_sql('agregated', con = engine,dtype={"name": sqlalchemy.types.VARCHAR (255), "no_of-products": sqlalchemy.types.INT}, if_exists = 'append', chunksize = 10000, index= False)

计数重复()```

于 2021-04-11T09:35:03.260 回答