To
insert a record into a
MySQL table using Python, you can use the `
INSERT INTO
` statement. Here's an example Python program that inserts a record into a `
customers
` table :
Example :
import mysql.connector
# Create a connection to the MySQL server
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
# Create a cursor object to execute SQL statements
mycursor = mydb.cursor()
# Insert a record into the table
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
# Commit the transaction
mydb.commit()
# Print a message to indicate success
print(mycursor.rowcount, "record inserted.")
# Close the connection
mydb.close()​