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 connect Python with MySQL using XAMPP?
- How do I use Python to query MySQL with multiple conditions?
- How can I retrieve unread results from a MySQL database using Python?
- How can I use Python to retrieve data from MySQL?
- How do I use Python to authenticate MySQL on Windows?
- How can I use Python and MySQL to create a login system?
- How can I connect Python to a MySQL database?
- How can I connect to MySQL using Python?
- How can I connect Python and MySQL?
See more codes...