Python MySql Insert records

Adding a record to the table

The INSERT INTO statement is used to add a record to the table. In python, we can mention the format specifier (--s) in place of values.

We provide the actual values in the form of tuple in the execute() method of the cursor.

Insert records Example

CopiedCopy Code

import mysql.connector  
myconn = mysql.connector.connect(host = "localhost", user = "root",password = "naveen",database = "PythonDB")  
cur = myconn.cursor()  
sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (--s, --s, --s, --s, --s)"  
val = ("Mark", 110, 25000.00, 201, "Newyork")  
try:  
    cur.execute(sql,val)  
    myconn.commit()  
      
except:  
    myconn.rollback()  
  
print(cur.rowcount,"record inserted!")  
myconn.close()