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
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How do I connect Python with MySQL using XAMPP?
- How can I use Python and MySQL to create a login system?
- How can I use Python and MySQL to generate a PDF?
- How do I use Python to connect to a MySQL database using XAMPP?
- How do Python and MySQL compare to MariaDB?
- How can I convert data from a MySQL database to XML using Python?
- How do I update a row in a MySQL database using Python?
- How do I set up a secure SSL connection between Python and MySQL?
- How can I use Python to retrieve data from MySQL?
See more codes...