bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Python/Databases in Python
Python•Databases in Python

Python MySQL Select From

Select From a Table

To select from a table in MySQL, use the "SELECT" statement:

Example

Select all records from the "customers" table, and display the result:

import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="
yourusername
",
password="
yourpassword
",
database="mydatabase"
)
mycursor =
mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
 print(x)

Note

We use the fetchall() method, which fetches all rows from the last executed statement.

Selecting Columns

To select only some of the columns in a table, use the "SELECT" statement followed by the column name(s):

Example

Select only the name and address columns:

import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="
yourusername
",
password="
yourpassword
",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT name,
address FROM
customers")
myresult = mycursor.fetchall()
for x in myresult:
 print(x)

Using the fetchone() Method

If you are only interested in one row, you can use the fetchone() method.

The fetchone() method will return the first row of the result:

Fetch only one row

import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="
yourusername
",
password="
yourpassword
",
database="mydatabase"
)
mycursor =
mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchone()
print(myresult)

Previous

Python MongoDB Insert Document

Next

Python MongoDB Find

This chapter

Overview
23

Lessons

49m

Read time

1. Python MySQL2. Python MongoDB3. Python MySQL Create Database4. Python MongoDB Create Database5. Python MySQL Create Table6. Python MongoDB Create Collection7. Python MySQL Insert Into Table8. Python MongoDB Insert Document9. Python MySQL Select From10. Python MongoDB Find11. Python MySQL Where12. Python MongoDB Query13. Python MySQL Order By14. Python MongoDB Sort15. Python MySQL Delete From By16. Python MongoDB Delete Document17. Python MySQL Drop Table18. Python MongoDB Drop Collection19. Python MySQL Update Table20. Python MongoDB Update21. Python MySQL Limit22. Python MongoDB Limit23. Python MySQL Join

On this page

Select From a TableSelecting ColumnsUsing the fetchone() Method