bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Python/Databases in Python
Python•Databases in Python

Python MySQL Select From

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Python MySQL Select From?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ mysql.connector
3Order

Put the learning moves in the order that makes the concept easiest to apply.

To select from a table in MySQL, use the "SELECT" statement:
Using the fetchone() Method
Select From a Table

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