chapter
Select (SELECT) from the data table
MySQL is selected from the table (SELECT) data, using the "SELECT" statement:
Examples
Selected from the "customers" table (SELECT) all records, and displays the results:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="你的用户名",
passwd="你的密码",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Note : We use a
fetchall()
method, which results from the last executed statement, gets all rows.
Select (SELECT) part of the field
To select part of the field in the table, using the "SELECT field 1, field 2 ..." statement:
Examples
Select name
and address
fields:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="你的用户名",
passwd="你的密码",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT name, address FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Using either fetchone () method
If you want to get a row, you can use fetchone()
the method.
fetchone()
The method returns the result of the first row:
Examples
Just take one line:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="你的用户名",
passwd="你的密码",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchone()
print(myresult)