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.connector
module, 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 themydb
variable. -
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 theemployees
table. -
myresult = mycursor.fetchall()
: fetches all the results of the query and stores them in themyresult
variable. -
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 connect to a MySQL database over SSH using Python?
- How can I use Python to retrieve data from MySQL?
- How can I connect Python and MySQL?
- How do I access MySQL using Python?
- How can I connect to MySQL using Python?
- How can I use Python and MySQL to create a login system?
- How do I use a cursor to interact with a MySQL database in Python?
- How do Python and MySQL compare to MariaDB?
- How can I keep a MySQL connection alive in Python?
- ¿Cómo conectar Python a MySQL usando ejemplos?
See more codes...