Connect to MySQL, create a table and insert records entered by the user
Expt. No.25
Page No.50
Create a table and insert records
Aim
To write a Python program that connects to a MySQL database, creates a STUDENT table and inserts records entered by the user using %s placeholders.
Concepts used
Algorithm
- Import mysql.connector and connect to the school database.
- Create a cursor and execute CREATE TABLE.
- For each student, input the values and execute INSERT with %s placeholders.
- Call commit() to save the changes.
- Execute SELECT and display the rows.
- Close the connection.
Program
# Create a table and insert records from Python import mysql.connector con = mysql.connector.connect(host="localhost", user="root", password="your_password", database="school")cur = con.cursor()cur.execute("CREATE TABLE student (rollno INT PRIMARY KEY, name VARCHAR(20), marks INT)") n = int(input("How many students? "))for i in range(n): roll = int(input("Roll number: ")) name = input("Name : ") marks = int(input("Marks : ")) cur.execute("INSERT INTO student VALUES (%s, %s, %s)", (roll, name, marks))con.commit()print(n, "records inserted") cur.execute("SELECT * FROM student")for row in cur.fetchall(): print(row)con.close()
A marked line continues the line above it. In your file, write it on the same line.
Change your_password to your own MySQL password before you run it.
Output
$ python pysql_create_insert.py
How many students? 3
Roll number: 1
Name : Asha
Marks : 82
Roll number: 2
Name : Rohan
Marks : 67
Roll number: 3
Name : Kabir
Marks : 91
3 records inserted
(1, 'Asha', 82)
(2, 'Rohan', 67)
(3, 'Kabir', 91)
✓ Printed by running this program, not typed by hand.
Result
The table was created from Python, three records were inserted with
%s placeholders and saved with commit(), and SELECT returned them as tuples.Viva voce: what the examiner may ask
01What is a cursor?
An object created from the connection that sends SQL statements to the database and holds the results.
02Why is commit() needed after INSERT?
It makes the changes permanent. Without it they are lost when the connection closes.
03Why use %s placeholders instead of joining strings?
The connector puts the values in safely and quotes strings for you.
04Which module is imported to connect Python with MySQL?
mysql.connector.
Variations for the lab test
- Insert records until the user types "n" for "add more?".
- Create a table for books and insert three books.
- Check
con.is_connected()before running the queries.
! Common mistake Forgetting
con.commit(): the program runs without errors but the records are not saved in the table.