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 can I use Python to interact with a MySQL database using YAML?
- How do I use Python to query MySQL with multiple conditions?
- How do I use Python to authenticate MySQL on Windows?
- How can I connect Python to a MySQL database?
- How do Python and MySQL compare to MariaDB?
- How do I use Python to update multiple columns in a MySQL database?
- How do I use Python to show the MySQL processlist?
- How can I connect Python and MySQL?
- How do I connect to XAMPP MySQL using Python?
See more codes...