新建config.py文件和opmysql.py文件
config.py
import os
src_path = os.path.dirname(os.path.dirname((os.path.realpath(__file__))))
# print(src_path)
# 当前脚本所在目录的上级目录的绝对路径 E:\PyCharm\pythonProject\2_book
opmysql.py
整体结构
整体结构代码
'''
对于MySQL数据库基本操作的封装
1.单条基本操作 删改更新
2.独立查询单条或多条数据
3.独立添加多条数据
'''
import logging,os,pymysql
from public import config
class OperationDbInterface(object):
# 初始化数据库连接
def __init__(self,host_db='localhost',user_db='root',passwd_db='123456',name_db='test_interface',
port_db=3306,link_type=0):
# 定义1.单条基本操作 删改更新
def op_sql(self,condition):
# 2.独立查询单条数据
def select_one(self,condition):
# 2.独立查询多条数据
def select_all(self,condition):
# 3.独立添加多条数据
def insert_data(self,condition,params):
# 关闭数据库
def __del__(self):
if __name__ == "__main__":
# 实例化
test = OperationDbInterface()
# 查询多条数据
result_select_all = test.select_all("select * from config_total")
# 查询单条数据
result_select_one=test.select_one("select * from config_total where id=1")
# 更改数据
result_op_sql = test.op_sql("update config_total set value_config='test' where id=1")
# 插入数据
result = test.insert_data("insert into config_total(key_config,value_config,description,status)"
"values (%s,%s,%s,%S)",[('mytest1','mytest11','我的测试 1',1),
('mytest2','mytest22','我的测试 2',0)])
print(result_select_all['data'],result_select_all['message'])
print(result_select_one['data'],result_select_one['message'])
print(result_op_sql['data'],result_op_sql['message'])
print(result['data'],result['message'