The Wayback Machine - https://web.archive.org/web/20240626160045/https://www.geeksforgeeks.org/python-mysql-insert-into-table/
Open In App

Python MySQL – Insert into Table

Last Updated : 27 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. Note: Before we insert data into our database, we need to create a table. In order to do so, refer to Python: MySQL Create Table.

Inserting data

You can insert one row or multiple rows at once. The connector code is required to connect the commands to the particular database. 

Connector query 

Python3




# Enter the server name in host
# followed by your user and
# password along with the database
# name provided by you.
 
import mysql.connector
 
 
mydb = mysql.connector.connect(
  host = "localhost",
  user = "username",
  password = "password",
  database = "database_name"
)
 
mycursor = mydb.cursor()


Now, the Insert into Query can be written as follows: Example: Let’s suppose the record looks like this – python-mysql-insert 

Python3




sql = "INSERT INTO Student (Name, Roll_no) VALUES (%s, %s)"
val = ("Ram", "85")
 
mycursor.execute(sql, val)
mydb.commit()
 
print(mycursor.rowcount, "details inserted")
 
# disconnecting from server
mydb.close()


Output:

1 details inserted

python-mysql-insert-2 To insert multiple values at once, executemany() method is used. This method iterates through the sequence of parameters, passing the current parameter to the execute method. Example: 

Python3




sql = "INSERT INTO Student (Name, Roll_no) VALUES (%s, %s)"
val = [("Akash", "98"),
       ("Neel", "23"),
       ("Rohan", "43"),
       ("Amit", "87"),
       ("Anil", "45"),
       ("Megha", "55"),
       ("Sita", "95")]
 
mycursor.executemany(sql, val)
mydb.commit()
 
print(mycursor.rowcount, "details inserted")
 
# disconnecting from server
mydb.close()


Output:

7 details inserted

python-mysql-insert-3 Note:

  • The cursor() is used in order to iterate through the rows.
  • Without the command mydb.commit() the changes will not be saved.

Python program that inserts a row into a MySQL table using the mysql-connector library:

Python




import mysql.connector
 
# Connect to the MySQL server
db = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="yourdatabase"
)
 
# Create a cursor object
cursor = db.cursor()
 
# Prepare the SQL query
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
values = ("John Smith", "123 Main St")
 
# Execute the query
cursor.execute(sql, values)
 
# Commit the changes
db.commit()
 
# Print the number of rows affected
print(cursor.rowcount, "record inserted.")


This program connects to a MySQL server and inserts a row into a table named customers with the name and address values provided. The mysql-connector library is used to interact with the MySQL server.

The time complexity of this program depends on the efficiency of the MySQL server and the size of the table being inserted into. The execute() function is generally fast, with a time complexity of O(1), but the actual time it takes to execute the query will depend on the size and complexity of the table.

The space complexity of this program is also O(1), as it doesn’t create any significant additional data structures beyond the values variable.

When run, this program should output a message indicating the number of rows affected by the query, which in this case should be 1.



Previous Article
Next Article

Similar Reads

How to insert values into MySQL server table using Python?
Prerequisite: Python: MySQL Create Table In this article, we are going to see how to get the size of a table in MySQL using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicatin
2 min read
Python MySQL - Insert record if not exists in table
In this article, we will try to insert records and check if they EXISTS or not. The EXISTS condition in SQL is used to check if the result of a correlated nested query is empty (contains no tuples) or not. It can be used to INSERT, SELECT, UPDATE, or DELETE statements. Pre-requisite Connect MySQL Database to PythonPythonInsert Record If Not Exists
4 min read
Insert Multiple Rows in MySQL Table in Python
MySQL is an open-source, Relational Database Management System (RDBMS) that stores data in a structured format using rows and columns. It is software that enables users to create, manage, and manipulate databases. So this is used in various applications across a wide range of industries and domains. To run the MySQL server in our systems we need to
5 min read
Get the id after INSERT into MySQL database using Python
Prerequisites: MySQL, mysql-connector for python The task here is to draft a Python program that works with SQL support to connect data. Whenever insertion into the database takes place, the ID of the row inserted will be printed. To connect python with the database we are using MySQL connector. The work of mysql-connector is to provide access to M
2 min read
PostgreSQL - Insert Data Into a Table using Python
In this article we will look into the process of inserting data into a PostgreSQL Table using Python. To do so follow the below steps: Step 1: Connect to the PostgreSQL database using the connect() method of psycopg2 module.conn = psycopg2.connect(dsn) Step 2: Create a new cursor object by making a call to the cursor() methodcur = conn.cursor() Ste
2 min read
Python MariaDB - Insert into Table using PyMySQL
MariaDB is an open source Database Management System and its predecessor to MySQL. The pymysql client can be used to interact with MariaDB similar to that of MySQL using Python. In this article we will look into the process of inserting rows to a table of the database using pymysql. You can insert one row or multiple rows at once. The connector cod
2 min read
Inserting data into a new column of an already existing table in MySQL using Python
Prerequisite: Python: MySQL Create Table In this article, we are going to see how to Inserting data into a new column of an already existing table in MySQL using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector Python modul
2 min read
Using Sqlalchemy to insert MySQL Timestamp Column Values
This article is about how we can add a timestamp column with values in MYSQL along with other data in an SQL database. Timestamp is quite useful as it provides the time when that particular entity was created in the database. Here we will use SQLAlchemy as it is a popular Python programming SQL toolkit and ORM (Object Relational Mapper) that gives
3 min read
Connect MySQL database using MySQL-Connector Python
While working with Python we need to work with databases, they may be of different types like MySQL, SQLite, NoSQL, etc. In this article, we will be looking forward to how to connect MySQL databases using MySQL Connector/Python.MySQL Connector module of Python is used to connect MySQL databases with the Python programs, it does that using the Pytho
2 min read
Python program to insert an element into sorted list
Given a sorted list and an element, Write a Python program to insert the element into the given list in sorted position. Examples: Input : list = [1, 2, 4], n = 3 Output : list = [1, 2, 3, 4] Input : list = ['a', 'b', 'c', 'd'], n = 'e' Output : list = ['a', 'b', 'c', 'd', 'e'] Approach #1 : This approach is the brute force method. Since the list i
9 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg