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()
相关推荐
Lyyaoo.1 小时前
【JAVA基础面经】JVM的内存模型
java·开发语言·jvm
杨凯凡1 小时前
【017】泛型与通配符:API 设计里怎么用省心
java·开发语言
Java后端的Ai之路1 小时前
Text-to-SQL与智能问数完全指南:基本概念、核心原理、Python实战教学及企业项目落地
数据库·python·sql·text-to-sql·智能问数
Elastic 中国社区官方博客1 小时前
Prometheus Remote Write 在 Elasticsearch 中的摄取原理
大数据·数据库·elasticsearch·搜索引擎·信息可视化·全文检索·prometheus
IT利刃出鞘1 小时前
Spring工具类--ObjectUtils的使用
java·后端·spring
2601_949816681 小时前
Spring boot启动原理及相关组件
数据库·spring boot·后端
2301_782659181 小时前
如何使用Navicat连接云端MariaDB_白名单与实例配置
jvm·数据库·python
2301_803875618 小时前
PHP 中处理会话数组时的类型错误解析与修复指南
jvm·数据库·python
m0_743623928 小时前
c++如何批量修改文件后缀名_std--filesystem--replace_extension【实战】
jvm·数据库·python
MY_TEUCK8 小时前
Sealos 平台部署实战指南:结合 Cursor 与版本发布流程
java·人工智能·学习·aigc