Python Select From

Select from the table

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

Example

Select all records from the table "customers" and display the results:

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

Run Instance

Note:We used fetchall() The method retrieves all lines from the last executed statement.

Select Columns

If you need to select only certain columns from the table, please use the "SELECT" statement followed by column names:

Example

Select Only Name and Address Columns:

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

Run Instance

Use the fetchone() method

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

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

Example

Get Only One Row:

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

Run Instance