Python Select From

Selecteer uit de tabel

Gebruik de "SELECT"-uitvoeringsinstructie om te kiezen uit een tabel in MySQL:

Example

Selecteer alle records van de tabel "customers" en toon het resultaat:

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

Opmerking:We hebben fetchall() Methode, deze methode haalt alle regels op uit de laatst uitgevoerde statement.

Select Columns

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

Example

Only select 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