Hello students in this article we will discuss about How we can insert Records in Database using python. Firstly we create connection between python and mysql using pip install mysql-connector-python. You can add new record/rows to an existing table of MySQL using the INSERT INTO statement. In this, you need to specify the name of the table, column names, and values (in the same order as column names).
PYTHON PROGRAM TO Insert record in Database
import mysql.connector
#establishing the connection
conn = mysql.connector.connect( user='root', password='0000', host='localhost')
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
cursor.execute("use mydb5")
#Preparing SQL query to INSERT a record into the database
#sql1 ="""CREATE TABLE EMPLOYEE6(FIRST_NAME CHAR(20) NOT NULL,LAST_NAME CHAR(20),
#AGE INT,SEX CHAR(1),INCOME int)"""
#cursor.execute(sql1)
sql ="INSERT INTO EMPLOYEE6 VALUES('Mac3','Mohan1', 21, 'O', 2000)"
# Executing the SQL command
cursor.execute(sql)
conn.commit()
# SECOND METHOD TO INSERT RECORD IN THE DATABASE
sql2 = "INSERT INTO EMPLOYEE6 VALUES (%s,%s, %s, %s, %s) "
val = ('Mac2','Mohani', 30, 'F', 3000)
cursor.execute(sql2, val)
conn.commit()
# Closing the connection
conn.close()
0 Comments