pymysql

查询所有结果---> cursor.fetchall()方法

存在修改操作,需要确认提交

1、手动提交---> conn.commit()

2、设置自动提交---> autocommit=True

python 复制代码
from pymysql import Connection

# 连接数据库
conn = Connection(
    host='localhost',   # 主机名(ip)
    port=3306,          # 端口号
    user='root',        # 用户名
    passwd='123456',    # 密码
    autocommit=True     # 设置自动提交
)
# 打印一下数据库服务器的版本号,也是确认数据库有没有连上
# print(conn.get_server_info())

# 获取游标对象
cursor = conn.cursor()
# 选择一个数据
conn.select_db("test")

# 使用游标对象,执行sql语句-->创建test_pymysql表,并且一个int类型的id字段
# cursor.execute("create table test_pymysql (id int);")

# 查询表
# cursor.execute("select * from test_pymysql")
# 使用cursor.fetchall()方法,查询所有结果
# result = cursor.fetchall()
# for r in result:
#     print(r)

# 插入一行
# cursor.execute("insert into test_pymysql values(3, '小小', 25, '女')")
# conn.commit()   # 手动确认提交

# 修改部分字段数据
cursor.execute("update test_pymysql set name='大大', age=23 where id=5")

# 关闭连接
conn.close()

实例:将数据写入数据库

python 复制代码
from data_reading.data_define import Record
from data_reading.file_define import TextFileReader, JsonFileReader
from pymysql import Connection

text_file_reader = TextFileReader("E:\\python\\销售数据.txt")
json_file_reader = JsonFileReader("E:\\python\\销售数据JSON.txt")

jan_data: list[Record] = text_file_reader.read_data()
feb_data: list[Record] = json_file_reader.read_data()

all_data: list[Record] = jan_data + feb_data

conn = Connection(
    host="localhost",
    port=3306,
    user="root",
    passwd="123456",
    autocommit=True
)
cursor = conn.cursor()
conn.select_db("py_sql")
# for record in all_data:
#     sql = ("insert into orders(order_date, order_id, money, province) values(%s, %s, %s, %s)")
#     params = ((record.date, record.order_id, record.money, record.province))
#     # print(sql)
#     cursor.execute(sql, params)

cursor.execute("select * from orders")
result = cursor.fetchall()
for i in result:
    print(i)

conn.close()
相关推荐
小安运维日记3 分钟前
RHCA - DO374 | Day01:使用红帽Ansible自动化平台开发剧本
运维·服务器·云原生·自动化·云计算·ansible
草明9 分钟前
clickhouse 检查是否有删除语句在执行
数据库·clickhouse
风语者日志21 分钟前
攻防世界—easyupload
数据库·web安全·ctf·小白入门
咬_咬24 分钟前
C++仿mudo库高并发服务器项目:Buffer模块
服务器·开发语言·c++·缓冲区·buffer·muduo库
刘岩Tony25 分钟前
ssh别名和多服务器同步文件
运维·服务器·ssh
zzy208874027125 分钟前
自定义服务器实现时间同步
运维·服务器
LXY_BUAA28 分钟前
在电脑中安装双系统(win11 + linux)20251019
linux·运维·服务器
小小爱大王29 分钟前
AI 编码效率提升 10 倍的秘密:Prompt 工程 + 工具链集成实战
java·javascript·人工智能
彡皮31 分钟前
qt实用学习案例:数据库设计+图表显示+model-view模式+样式表定制
数据库·qt·学习
神龙斗士2401 小时前
继承和组合
java·开发语言