Lokang 

Python and MySQL

python mysql insert

To insert data into a MySQL database using Python, you can use the "mysql-connector-python" library. Here are the steps to insert data into a MySQL database using Python:

Install the mysql-connector-python library using pip. You can use the following command to install it:

pip install mysql-connector-python

Import the mysql.connector module in your Python script. You can do this using the following code:

import mysql.connector

Establish a connection to your MySQL server using the mysql.connector.connect() method. This method takes several parameters, including the host name, user name, password, and database name. Here is an example:

mydb = mysql.connector.connect(
 host="localhost",
 user="yourusername",
 password="yourpassword",
 database="mydatabase"
)

Once you have established a connection, you can create a new cursor object using the connection object and execute an SQL INSERT statement to insert data into a table. Here is an example:

mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")

In this example, we are inserting a new record into a "customers" table with the "name" and "address" columns. We use the %s placeholder syntax to insert values into the SQL statement, and pass the actual values in a tuple to the execute() method.

Finally, we commit the transaction using the commit() method of the connection object. The rowcount attribute of the cursor object returns the number of rows affected by the SQL statement.

The complete Python code to insert data into a MySQL database using mysql-connector-python would look like this:

import mysql.connector
mydb = mysql.connector.connect(
 host="localhost",
 user="yourusername",
 password="yourpassword",
 database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")

In this code, you will need to replace "yourusername" and "yourpassword" with the actual values for your MySQL server, and "mydatabase" with the name of your database. Once you run this code, it will insert a new record into the "customers" table and print out the number of records inserted.