如需从 MySQL 中的表中进行选择,请使用 "SELECT" 语句:
从表 "customers" 中选取所有记录,并显示结果:
import mysql.connectormydb = 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)
注释:我们用了 fetchall() 方法,该方法从最后执行的语句中获取所有行。
如需只选择表中的某些列,请使用 "SELECT" 语句,后跟列名:
仅选择名称和地址列:
import mysql.connectormydb = 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)
如果您只对一行感兴趣,可以使用 fetchone() 方法。
fetchone() 方法将返回结果的第一行:
仅获取一行:
import mysql.connectormydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword", database="mydatabase")mycursor = mydb.cursor()mycursor.execute("SELECT * FROM customers")myresult = mycursor.fetchone()print(myresult)