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 theMySQLdblibrarydb = 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 convert a MySQL query to JSON using Python?
- How do I perform a MySQL health check using Python?
- How can I use Python and MySQL together to perform asynchronous operations?
- How can I use Python to retrieve data from MySQL?
- How can I connect Python to a MySQL database?
- How do I set up a secure SSL connection between Python and MySQL?
- How do I download MySQL-Python 1.2.5 zip file?
- How do I install a Python package from PyPI into a MySQL database?
- How can I use Python and MySQL to generate a PDF?
See more codes...