0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

will try that function. In case that the table is already there, do I need to name the columns in df precisely like the name in SQL table?
Yeah the column name in df and the sql table should match

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.