python-mysqlHow do I execute a query in MySQL using Python?
To execute a query in MySQL using Python, you must first create a connection to the database. This can be done using the mysql.connector module. The following example code creates a connection to a MySQL database and executes a query to select all records from the employees table:
import mysql.connector
# Create connection to the database
mydb = mysql.connector.connect(
host="localhost",
user="username",
passwd="password",
database="mydatabase"
)
# Execute query
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM employees")
# Output query results
myresult = mycursor.fetchall()
for x in myresult:
print(x)
The code above will output the results of the query, for example:
(1, 'John', 'Doe', '[email protected]')
(2, 'Mary', 'Moe', '[email protected]')
(3, 'Julie', 'Dooley', '[email protected]')
The code consists of the following parts:
-
import mysql.connector: imports themysql.connectormodule, which contains the functions needed to connect to a MySQL database. -
mydb = mysql.connector.connect(...): creates a connection to the MySQL database. The connection is stored in themydbvariable. -
mycursor = mydb.cursor(): creates a cursor object, which is used to execute the query. -
mycursor.execute("SELECT * FROM employees"): executes the query to select all records from theemployeestable. -
myresult = mycursor.fetchall(): fetches all the results of the query and stores them in themyresultvariable. -
for x in myresult: print(x): iterates through the results of the query and prints them.
For more information on connecting to and executing queries in MySQL using Python, see the following links:
More of Python Mysql
- How can I use Python and MySQL to generate a PDF?
- How can I create a web application using Python and MySQL?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How can I connect to MySQL using Python?
- How can I connect Python to a MySQL database?
- How do I connect Python with MySQL using XAMPP?
- How do I use Python to query MySQL with multiple conditions?
- How do I decide between using Python MySQL and PyMySQL?
- How can I use the Python MySQL API to interact with a MySQL database?
- How do I use a WHERE query in Python and MySQL?
See more codes...