用Python操作MySQL代码

本文介绍了使用Python操作MySQL数据库的全过程,包括新建config.py和opmysql.py文件,初始化数据库连接,解决找不到public包和路径错误的问题,处理中文乱码,进行数据的更新、删除、查询和插入操作,最后讲解如何关闭数据库连接。详细阐述了每一步的具体代码和遇到的问题及解决方案。
摘要由CSDN通过智能技术生成

新建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'
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值