python-mysqlHow do I format a MySQL query in Python?
The Python Database API Specification v2.0 provides a common interface for various database systems. To access MySQL databases from Python, you need to install the MySQL Connector/Python package.
To format a MySQL query in Python, you need to use the following syntax:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers WHERE address = %s"
adr = ("Yellow Garden 2", )
mycursor.execute(sql, adr)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
The output of the above code will be:
('John', 'Highway 21', 'Yellow Garden 2')
The code consists of the following parts:
import mysql.connector: imports the MySQL Connector/Python package.mydb = mysql.connector.connect(): creates a connection to the MySQL database.mycursor = mydb.cursor(): creates a cursor to execute the query.sql = "SELECT * FROM customers WHERE address = %s": defines the SQL query.adr = ("Yellow Garden 2", ): defines the parameters for the query.mycursor.execute(sql, adr): executes the query with the parameters.myresult = mycursor.fetchall(): fetches the results of the query.for x in myresult:: loops through the results.print(x): prints each result.
For more information, please refer to the MySQL Connector/Python documentation.
More of Python Mysql
- How can I create a web application using Python and MySQL?
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database?
- How do I connect Python with MySQL using XAMPP?
- How can I access MySQL using Python?
- How can I connect Python and MySQL?
- How do I use Python to query MySQL with multiple conditions?
- How do I use Python to authenticate MySQL on Windows?
- How can I convert data from a MySQL database to XML using Python?
- How do I use a cursor to interact with a MySQL database in Python?
See more codes...