Inserting rows

(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

Insert statement is used to insert records in mysql.

Syntax: INSERT INTO <some table> (<some column names>) VALUES("<some values>");

Example 1:


This programs inserts a new city in the city table, notice the use to db.commit(), this method saves your changes to the database .

Example 2:

Notice the use of \  in line 18, \  is used to split python statements to multiple lines.

Inserting multiple rows

To insert multiple rows in the table use executemany()  method of cursor object.

Syntax: cursor_object.executemany(statement, arguments)

statement: string containing the query to execute.

arguments: a sequence containing values to use within insert statement.

Let’s take an example.


Other Tutorials (Sponsors)

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

6 thoughts on “Inserting rows

  1. Labyras

    I could not find the db.commit command anywhere on the internet, it was the missing piece in my code. Thank you so much!

  2. Cliff

    In the example of Inserting multiple rows, what is the purpose of the lines from line number 12 to line number 18? I’m just wondering.

  3. AN

    Thanks for the help, I have used your example and managed:
    cursor.execute(‘INSERT INTO [TABLE] ([TIMEID],[DATEID],[Hour],[DOW]) values (?,?,?,?)’, row[‘TIMEID’], row[‘DATEID’], row[‘Hour’], row[‘DOW’])

    How can i do a similiar to update the column values of say [Hour],[DOW] by reference to TIMEID??


Leave a Reply

Your email address will not be published. Required fields are marked *