python------Pymysql模块

查询

总结:
fetchall(): 获取所有查询到的内容。返回结果是嵌套的元组
fetchone(): 获取一条数据。返回结果就是一个非嵌套的元组
fetchmany(num): 返回结果是元组嵌套,底层也是有游标的。如果不传递参数num,默认读取一条数据

注意: 与文件读取类似,读取查询的数据内容的时候,底层有个游标。你读取到了什么地方,就会移动到那个地方。后续会接着从那个地方开始读

注意: execute的结果,代表的是影响的行数,并不是满足条件的数据条数

可能遇到的错误 :TypeError: object supporting the buffer API required

原因:是因为password的类型需要是字符串

python 复制代码
# 创建数据库命令 create database 库名 char set utf8;
import pymysql as mysql

"""
    TypeError: object supporting the buffer API required
    原因:是因为password的类型需要是字符串
"""
# 1- 创建连接
conn = mysql.connect(host='192.168.88.161',port=3306,database='day08',user='root',password='123456',charset='utf8')

# 2- 通过连接获得游标
cur = conn.cursor()

# 3- 通过游标执行SQL语句
# 查询的sql语句
query_sql = "select id,name from students"
result = cur.execute(query_sql)
print(result)

# 获取查询的数据内容
"""
    (
        (1, '张三'), (2, '李四'), (3, '王五')
    )
"""
# fetch_all_result = cur.fetchall()
# print(type(fetch_all_result),fetch_all_result)

print("-"*30)
"""
    注意:读取查询的数据内容的时候,底层有个游标,你读取到了什么地方,就会移动到那个地方。后续会接着从那个地方开始读
"""
# fetchone:返回的结果就是一条数据,没有元组的嵌套(1, '张三')
fetch_one_result = cur.fetchone()
print(type(fetch_one_result),fetch_one_result)

# print("-"*30)
#
# fetch_one_result = cur.fetchone()
# print(type(fetch_one_result),fetch_one_result)

print("="*30)
"""
fetchmany(num):返回结果是元组嵌套,底层也是有游标的。((3, '王五'),)。
                如果不传递参数num,默认读取一条数据
"""
fetch_many_result = cur.fetchmany(3)
print(type(fetch_many_result),fetch_many_result)
# fetch_many_result = cur.fetchmany()
# print(type(fetch_many_result),fetch_many_result)
# 4- 关闭游标
cur.close()
# 5- 关闭连接
conn.close()

增删改

python 复制代码
"""
pmysql增、删、改操作
"""
# ① 导入模块
import pymysql
# ② 创建连接
conn = pymysql.connect(host='192.168.88.131', port=3306,
                       user='root', password='itcast',
                       database='test', charset='utf8')
# ③ 创建游标
cursor = conn.cursor()
# 开启事务
conn.begin()
# ④ 执行SQL
insert_sql = 'insert into students values("Tom", 25, "male", 2.9)'
cursor.execute(insert_sql)
select_sql = 'select * from students'
cursor.execute(select_sql)
# 获取查询的结果
res = cursor.fetchall()
print(res)
# 提交事务
# 必须要进行事务的提交
conn.commit()
# ⑤ 关闭游标
cursor.close()
# ⑥ 关闭连接
conn.close()
# DELETE FROM students WHERE name = 'Tom';
# SELECT * FROM students;
相关推荐
凤城老人12 小时前
C++使用拉玛努金公式计算π的值
开发语言·c++·算法
HAH-HAH14 小时前
【Python 入门】(2)Python 语言基础(变量)
开发语言·python·学习·青少年编程·个人开发·变量·python 语法
递归不收敛14 小时前
一、Java 基础入门:从 0 到 1 认识 Java(详细笔记)
java·开发语言·笔记
SunnyDays101115 小时前
Python 轻松实现替换或修改 PDF 文字
python·替换pdf文字·修改pdf·修改pdf文字
Just_Paranoid15 小时前
【Settings】恢复出厂设置密码校验
android·python·settings·sha256·hmac-sha256
zhangfeng113315 小时前
win7 R 4.4.0和RStudio1.25的版本兼容性以及系统区域设置有关 导致Plots绘图面板被禁用,但是单独页面显示
开发语言·人工智能·r语言·生物信息
西猫雷婶17 小时前
pytorch基本运算-Python控制流梯度运算
人工智能·pytorch·python·深度学习·神经网络·机器学习
子午17 小时前
Python的uv包管理工具使用
开发语言·python·uv
java1234_小锋17 小时前
Scikit-learn Python机器学习 - 分类算法 - 朴素贝叶斯
python·机器学习·scikit-learn
凡梦千华17 小时前
Django时区感知
后端·python·django