栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 数据库 > MySQL

python连接数据库后怎样查询

MySQL 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python连接数据库后怎样查询

Python查询Mysql使用fetchone()方法获取单条数据,使用fetchall()方法获取多条数据。

fetchone():该方法获取下一个查询结果集。结果集是一个对象

fetchall():接收全部的返回结果行。

rowcount:这是一个只读属性,并返回执行execute()方法后影响的行数。

1、使用fetchone()方法获取结果集

import pymysql
 
# 打开数据库连接
db = pymysql.connect("localhost", "root", "123456", "test")
 
# 使用cursor()方法获取操作游标
cursor = db.cursor()
 
# SQL 查询语句
sql = "SELECt * FROM EMPLOYEE 
       WHERe INCOME > '%d'" % (1000)
try:
    # 执行SQL语句
    cursor.execute(sql)
    print(cursor.rownumber)
    result = cursor.fetchone()
    while result!=None:
        print(result, cursor.rownumber)
        result = cursor.fetchone()
 
    result = cursor.fetchone()
    print(result, cursor.rownumber)
    result = cursor.fetchone()
    print(result, cursor.rownumber)
 
except:
   print ("Error: unable to fetch data")
 
# 关闭数据库连接
db.close()
 
 
输出结果:
 
0
('Mac', 'Mohan', 20, 'M', 2000.0) 1
('Marry', 'Mohan', 32, 'M', 3000.0) 2
('Bob', 'Mohan', 21, 'F', 4000.0) 3
None 3
None 3

结论:

执行cursor.execute(SQL)语句后,光标指向第一条记录之前的位置。

执行cursor.fetchone()语句之后,fetchone()方法返回光标指向的下一条记录,同时光标指向当前记录的下一条记录。

当光标已经指向最后一条记录时,再次执行cursor.fetchone()语句后,结果返回无,光标不再向前移动。

2:fetchall():接收全部的返回结果行

import pymysql
 
# 打开数据库连接
db = pymysql.connect("localhost", "root", "123456", "test")
 
# 使用cursor()方法获取操作游标
cursor = db.cursor()
 
# SQL 查询语句
sql = "SELECt * FROM EMPLOYEE 
       WHERe INCOME > '%d'" % (1000)
try:
    # 执行SQL语句
    cursor.execute(sql)
    # 获取所有记录列表
    results = cursor.fetchall()
    for row in results:
        fname = row[0]
        lname = row[1]
        age = row[2]
        sex = row[3]
        income = row[4]
        # 打印结果
        print("fname=%s,lname=%s,age=%d,sex=%s,income=%d" %
              (fname, lname, age, sex, income))
except:
   print ("Error: unable to fetch data")
 
# 关闭数据库连接
db.close()

更多技术请关注python视频教程。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/13828.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号