Insert into tables in MySQL using Python




In this post, we will see how to insert a table into a MySQL database.

Connecting to database

First, we need to connect to our database,

import mysql.connector 

mydb = mysql.connector.connect( 
host = "localhost", 
user = "username", 
password = "password", 
database = "database_name"
) 

mycursor = mydb.cursor() 

This code will connect to our database.

Inserting a single row

sql = "INSERT INTO Users (Name, Phone, Language) VALUES (%s, %s, %s)"
val = ("XXXXX", "XXXXXXX", "XXXXX") 

mycursor.execute(sql, val) 
mydb.commit() 

print(=="details inserted") 
print(mycursor.rowcount)
mydb.close() 

Inserting multiple rows

sql = "INSERT INTO Users (Name, Phone, Language) VALUES (%s, %s, %s)"
val = [("XXXXX", "XXXXX", "XXXXXX"), 
	("XXXXX", "XXXXX", "XXXXXX"))] 

mycursor.executemany(sql, val) 
mydb.commit() 

print("details inserted") 
print(mycursor.rowcount, )

# disconnecting from server 
mydb.close()