python-mysqlHow do I use Python to build MySQL queries?
Using Python to build MySQL queries is a great way to make sure your queries are well-constructed and accurate. Here is an example of how to do it:
#import the mysql.connector library/module
import mysql.connector
#establish connection to MySQL
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="password",
database="mydatabase"
)
#create cursor
mycursor = mydb.cursor()
#build query
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
#execute query
mycursor.execute(sql, val)
#commit changes to database
mydb.commit()
#print number of records inserted
print(mycursor.rowcount, "record inserted.")
Output example
1 record inserted.
The code above can be broken down as follows:
import mysql.connector
- imports the mysql.connector library/module so you can use its functions.mydb = mysql.connector.connect()
- establishes a connection to the MySQL database using the parameters provided.mycursor = mydb.cursor()
- creates a cursor object which allows you to execute queries.sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
- builds a SQL query to insert data into the customers table.val = ("John", "Highway 21")
- specifies the values to be inserted into the customers table.mycursor.execute(sql, val)
- executes the query with the provided values.mydb.commit()
- commits the changes to the database.print(mycursor.rowcount, "record inserted.")
- prints the number of records inserted.
For more information on using Python to build MySQL queries, check out the MySQL Connector/Python Developer Guide.
More of Python Mysql
- How do I access MySQL using Python?
- How can I use Python to retrieve data from MySQL?
- How can I connect to MySQL using Python?
- How can I access MySQL using Python?
- How can I connect Python to a MySQL database?
- How can I use Python to interact with a MySQL database using YAML?
- How do I connect Python with MySQL using XAMPP?
- How can I use Yum to install the MySQLdb Python module?
- How can I use Python to interact with a MySQL database?
- How do I use a Python variable in a MySQL query?
See more codes...