千纸鹤

  博客园  ::  :: 新随笔  ::  ::  :: 管理
  5 随笔 :: 70 文章 :: 0 评论 :: 9301 阅读
class14 项目名
一、db.conf:配置文件
[TEST_DB]
host=127.0.0.1
port=3306
user=root
password=123456
database=mytest2
charset=utf8

[ZS_DB]
host=127.0.0.1
port=3306
user=root
password=123456
database=mytest2
charset=utf8

二、demo2.py类文件:MysqlDb方法
import pymysql
import configparser
class MysqlDb:
# __init__初始化函数:只要实例化这个类就会调用init
# 连接数据库和创建游标
# 读取配置文件
# configpath读取的是哪个文件 db 文件中的哪个数据
def __init__(self,configpath,db):
# 实例config工具
config=configparser.ConfigParser()
# 读取文件数据
config.read(configpath)
host=config[db]['host']
port=int(config[db]['port'])
user = config[db]['user']
password = config[db]['password']
database = config[db]['database']
charset = config[db]['charset']
try:
self.con = pymysql.connect(host=host, port=port, user=user, password=password, database=database,charset=charset)
except Exception as e:
print('初始化连接失败'%e)
self.cur=self.con.cursor()
# 查询数据
def select_query(self,sql):
try:
# 执行sql
self.cur.execute(sql)
# 有结果 拿到结果 fetchone()一条结果 fetchall()全部显示 fetchmany(指定显示几条数据)
result=self.cur.fetchmany(2)
return result
except Exception as e:
print('查询失败'%e)
# 增加删除修改数据
def AddDelUpd_query(self,sql):
try:
# 执行sql
self.cur.execute(sql)
self.cur.execute('commit')
return True
except Exception as e:
print('增删改失败'%e)

三、test.py类文件:
from class14.demo2 import MysqlDb

a = MysqlDb('db.conf','TEST_DB')
# 查询
query = a.select_query('select * from student3')
# 新增、删除、修改
add = a.AddDelUpd_query('insert into student3(id,name,age,sex) values(10,'大铁锤',30,'男')')
del = a.AddDelUpd_query('delete from student3 where id=10')
upd = a.AddDelUpd_query('update student3 set name='铁柱' where id=10')
print(add)
print(del)
print(upd)
posted on   隆江猪脚饭  阅读(56)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示