Python 如何在dataframe.to_sql中指定Int?
我正在尝试从数据库中获取数据,并尝试将其写入另一个表中,但由于某些原因,dataframe.to_sql抛出错误:Python 如何在dataframe.to_sql中指定Int?,python,dataframe,pandas-to-sql,Python,Dataframe,Pandas To Sql,我正在尝试从数据库中获取数据,并尝试将其写入另一个表中,但由于某些原因,dataframe.to_sql抛出错误: > engine = create_engine("mysql+pymysql://{user}:{pw}@localhost/{db}" .format(user="root", pw="dhanusha",
> 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'")
确保数据类型匹配。在df.to_sql中传递的表列类型和数据类型应匹配: 重复计数(): ```引擎=创建引擎(“mysql+pymysql://{user}:{pw}@localhost/{db}” .format(user=“root”, pw=“dhanusha”, db=“postmanasignment”),pool_pre_ping=True)
execute(“如果不存在表,则创建表(名称VARCHAR(255)), 没有_个产品(BIGINT UNSIGNED,主键(名称))) mycursor.execute(“按名称从产品组中选择名称、计数(id)) 结果=dict(mycursor.fetchall()) new=pd.DataFrame(result.items(),columns=['name','no\u of\u products']) new.to_sql('agregated',con=engine,dtype={“name”:sqlalchemy.types.VARCHAR(255), “没有产品”:sqlalchemy.types.INT},如果存在='append', chunksize=10000,index=False) 重复计数()```