求知 文章 文库 Lib 视频 iPerson 课程 认证 咨询 工具 讲座 Modeler   Code  
会员   
要资料
 
追随技术信仰

随时听讲座
每天看新闻
 
 
Python MySQL教程
1. Python_MySQL入门
2. Python 创建数据库
3. Python 创建表
4. Python 插入表
5. Python 从表中选取
6. Python 使用筛选器来选取
7. Python 结果排序
8. Python 删除记录
9. Python 删除表
10. Python 更新表
11. Python 限定结果
12. Python 加入
 

 
目录
Python Select From
45 次浏览
5次  

从表中选取

如需从 MySQL 中的表中进行选择,请使用 "SELECT" 语句:

实例

从表 "customers" 中选取所有记录,并显示结果:

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)

运行实例 »

注释: 我们用了 fetchall() 方法,该方法从最后执行的语句中获取所有行。

选取列

如需只选择表中的某些列,请使用 "SELECT" 语句,后跟列名:

实例

仅选择名称和地址列:

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)

运行实例 »

使用 fetchone() 方法

如果您只对一行感兴趣,可以使用 fetchone() 方法。

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

实例

仅获取一行:

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)

运行实例 »


您可以捐助,支持我们的公益事业。

1元 10元 50元





认证码: 验证码,看不清楚?请点击刷新验证码 必填



45 次浏览
5次