Python MySQL Select


章节


从表中选取(SELECT)数据

从MySQL表中选取(SELECT)数据,使用“SELECT”语句:

示例

从“customers”表中选取(SELECT)所有记录,并显示结果:

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)

注意: 我们使用了fetchall()方法,它从最后所执行语句的结果中,获取所有行。

选取(SELECT)部分字段

如果要选取表中的部分字段,使用“SELECT 字段1, 字段2 ...”语句:

示例

选择nameaddress字段:

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)

使用fetchone()方法

如果只想获取一行记录,可以使用fetchone()方法。

fetchone()方法将返回结果的第一行:

示例

只取一行:

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)

猜你喜欢

转载自www.cnblogs.com/jinbuqi/p/11588811.html