简体   繁体   中英

how to specify Int in dataframe.to_sql?

I am trying to fetch data from my database and trying to write it into another table but for some reason the dataframe.to_sql throws an error:

> 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'")

Make sure the datatypes match. the table column type and the dtype passed in your df.to_sql should match:

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)

count_duplicate()```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM