Python MySQL – Insert data in Table
In this tutorial, we will learn how to insert a single row and insert multiple rows of data in a MySQL table using Python.
To Insert data into a MySQL Table or to add data to the MySQL Table which we have created in our previous tutorial, We will use the INSERT
SQL statement.
If you are new to SQL, you should first learn about the SQL INSERT statement.
Python MySQL – INSERT
Data
Let us see the basic syntax to use INSERT INTO
statement to insert data into our table:
We can insert data in a table in two ways:
-
Inserting a single row at a time
-
Inserting multiple rows at a time
Inserting Single Row in MySQL Table
In this section, we will see the code example for inserting a single row of data in a MySQL table:
We will be adding data to the students table we created in Python MySQL – Create Table tutorial.
The output of the above code will be:
1 record inserted
Inserting Multiple Rows in MySQL Table
In this section, we will see the code example for inserting multiple rows of data in a MySQL table.
To insert multiple rows into the table, the executemany()
method is used. It takes a list of tuples containing the data as a second parameter and the query as the first argument.
If all three rows were entered successfully, the output of the above code will be:
3 records inserted
So in this tutorial we learned how we can insert data into MySQL table in Python.