Python Program to insert user input data into a table using MySQL


In this program, you will learn how to insert user input data into a table using Python and MySQL.


create database xiith;

use xiith;

create table emp(id varchar(10), name varchar(30),salary int(10))

select * from emp;

Example: How to insert user input data into a table using Python and MySQL.

import mysql.connector

id = input("Enter Emp id:")
name = input("Enter Emp name:")
salary = int(input("Enter Emp salary:"))

myconn = mysql.connector.connect(host="localhost", user="root", passwd="12345678", database="xiith")
cur = myconn.cursor()
sql = "insert into emp(id, name, salary) values(%s, %s, %s)"

val = (id, name, salary)
try:
    cur.execute(sql, val)

    myconn.commit()
except:
    myconn.rollback()
print(cur.rowcount, "record inserted!")
myconn.close()

Output:

Enter Emp id:102
Enter Emp name:Mike
Enter Emp salary:40000
1 record inserted!
python mysql insert by user input