Google News
logo
Python Program to Insert a record in a table
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()​
In this example, the program creates a connection to the MySQL server and a cursor object to execute SQL statements, just like in the previous examples.

To insert a record into the `customers` table, the program uses the `execute()` method of the cursor object to execute an `INSERT INTO` statement. The statement specifies the table name (`customers`) and the column names (`name` and `address`) into which the record will be inserted.

The values to be inserted are provided in a tuple (`val`), which is passed as a second parameter to the `execute()` method. Note that the `%s` placeholders in the statement are used to prevent SQL injection attacks and to properly escape any special characters in the input data.

After the record has been inserted, the program calls the `commit()` method of the connection object to commit the transaction. Finally, the program prints a message to indicate the number of records inserted and closes the connection.

Note that in a production environment, you should always validate input data and use parameterized queries to prevent SQL injection attacks.