python-mysqlHow do I use a SELECT statement in Python to query a MySQL database?
In order to use a SELECT statement in Python to query a MySQL database, the following steps should be taken:
- Establish a connection to the MySQL database using the
mysql.connector
library:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
- Create a cursor object by calling the
cursor()
method of the connection object:
mycursor = mydb.cursor()
- Use the
execute()
method of the cursor object to execute the SELECT statement:
mycursor.execute("SELECT * FROM customers")
- Fetch all the records from the SELECT statement using the
fetchall()
method of the cursor object:
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Output example
('John', 'Highway 21')
('Amy', 'Mountain 21')
('Hannah', 'Valley 345')
- Close the cursor and the connection to the database using the
close()
method of the cursor and connection objects respectively:
mycursor.close()
mydb.close()
Helpful links
More of Python Mysql
- How do I connect Python to a MySQL database using Visual Studio Code?
- How do I use Python to show the MySQL processlist?
- How can I resolve the "no database selected" error when using Python and MySQL?
- How do I access MySQL using Python?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I connect to MySQL using Python?
- How can I use Python and MySQL to create a login system?
- How can I connect Python to a MySQL database?
- How can I export data from a MySQL database to a CSV file using Python?
- How do I insert a datetime value into a MySQL database using Python?
See more codes...