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()
相关推荐
getapi5 小时前
shareId 的产生与传递链路
java
手握风云-5 小时前
MySQL数据库精研之旅第十六期:深度拆解事务核心(上)
数据库·mysql
boonya6 小时前
Redis核心原理与面试问题解析
数据库·redis·面试
我没想到原来他们都是一堆坏人6 小时前
(未完待续...)如何编写一个用于构建python web项目镜像的dockerfile文件
java·前端·python
沙二原住民7 小时前
提升数据库性能的秘密武器:深入解析慢查询、连接池与Druid监控
java·数据库·oracle
三毛20047 小时前
玳瑁的嵌入式日记D33-0908(SQL数据库)
jvm·数据库·sql
叫我龙翔7 小时前
【MySQL】从零开始了解数据库开发 --- 库的操作
数据库·mysql·数据库开发
Jerry&Grj7 小时前
SpringBoot埋点功能技术实现方案深度解析:架构设计、性能优化与扩展性实践
java·微服务·性能优化·springboot·架构设计·埋点技术
没有bug.的程序员7 小时前
Redis Stream:轻量级消息队列深度解析
java·数据库·chrome·redis·消息队列