How to Insert a Record in Python MySQL


In this example we will show how to insert a record in Python MySQL.

Source Code

import mysql.connector

# connect to server
mydb = mysql.connector.connect(
    host="localhost",
    port=3306,
    user="yourusername",
    password="yourpassword",
    db="mydatabase"
)

# get a cursor
mycursor = mydb.cursor()

sql = "INSERT INTO US_STATE (State_name, Abbreviation, Capital, Total_area) VALUES (%s, %s, %s, %s)"
add_val = ('Alabama', 'AL', 'Montgomery', 52420)

# execute a query
mycursor.execute(sql, add_val)

# put the change into effect
mydb.commit()

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

# close the connection
mydb.close()

Output:

1 record inserted.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments