python-mysqlHow can I use variables in a MySQL query with Python?
Using variables in a MySQL query with Python can be done using the MySQLdb
library.
An example of this is shown below:
import MySQLdb
# Open database connection
db = MySQLdb.connect("hostname","username","password","database_name" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = "INSERT INTO table_name(column_1,column_2) VALUES (%s,%s)"
# Execute the SQL command
cursor.execute(sql, (variable_1,variable_2))
# Commit your changes in the database
db.commit()
In this example, we use the MySQLdb
library to connect to a MySQL database. We then prepare a SQL query to insert a record into the database, with %s
placeholders for the variables. The variables are then passed into the cursor.execute()
method, and the changes are committed to the database.
The parts of the code are as follows:
import MySQLdb
- imports theMySQLdb
librarydb = MySQLdb.connect("hostname","username","password","database_name" )
- connects to the databasecursor = db.cursor()
- creates a cursor objectsql = "INSERT INTO table_name(column_1,column_2) VALUES (%s,%s)"
- prepares the SQL querycursor.execute(sql, (variable_1,variable_2))
- executes the SQL query with the variablesdb.commit()
- commits the changes to the database
Helpful links
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 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 Python to make a MySQL request?
- How do I insert NULL values into a MySQL table using Python?
- How can I connect to MySQL using Python?
- How can I use Python to interact with a MySQL database?
- How can I convert data from a MySQL database to XML using Python?
See more codes...