I need your help.
I have a list of information, which in form of list= [x0, x1,...x_end] ( with x0 = [name, phone number....] => about 25 details of one person)
I change the list into a dataframe, and now I want to push the data into SQL server database.
I use this line of code to insert a single data point to my database
cursor.execute('''
INSERT INTO Table (name of all the columns)
VALUES
(all value of a certain row)
''')
conn.commit()
now I want to push all the rows from list or from dataframe to the database.
I try something like:
def insert_sql(x):
cursor.execute('''INSERT INTO Table (name of all the columns) VALUES(x)''')
conn.commit()
for i in list:
insert_sql(i)
But it doesn't work.
Any idea? Also, there are many columns. Is there any way to automatically insert the row without listing all the name of the columns like what I did above?
Pandas provide a function to directly write your dataframe to DB, use the below function
DataFrame.to_sql(name, con, schema=None, if_exists='fail', index=True, index_label=None, chunksize=None, dtype=None, method=None)
First create a Table:
cursor.execute('CREATE TABLE Table_name (Brand text, Price number)')
conn.commit()
Next insert the records using to_sql:
your_df.to_sql('Table_name', conn, if_exists='replace', index = False)
Ref: to_sql
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.