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;
相关推荐
日日大王学编程6 分钟前
LangGraph 基本用法详解:从入门到实战
python·语言模型·langchain
威哥爱编程7 分钟前
Python 智能体开发实战 04:模型答得挺漂亮,程序却读不懂?让回答直接变成能入库的 JSON
python·agent
geovindu8 分钟前
rust: Read-Write Lock Pattern
开发语言·后端·设计模式·rust·读写锁模式·同步型模式
怪我冷i8 分钟前
Rust智能指针Rc<T> 使用总结
开发语言·后端·rust
全栈陈序员11 分钟前
【Python】基础语法入门(三十)—— Web 开发入门:用 Flask 搭建第一个网站
前端·python·flask
全栈陈序员15 分钟前
【Python】基础语法入门(三十三)—— 日志系统详解:用 logging 记录程序运行
java·开发语言·python
ESDWAN16 分钟前
SD-WAN 是什么?工作原理、适用场景与选型要点
开发语言·网络·数据库·架构·php
晗夜未央23 分钟前
跨仓库 Skill 换台电脑就失效?用 Git remote 校验项目
人工智能·git·python
Zack_Liu29 分钟前
code样例
pytorch·python·深度学习
wusam32 分钟前
基于HCL的python脚本编程(4)
网络·python·智能路由器