python的配置文件ConfigParser&通过配置文件实现数据库登录参数化

"""
settings.py  --python配置文件
.ini   --pytest配置文件
.yaml  --httprunner接口测试工具
 
1、创建一个.ini的配置文件。[section] option=value
2、python读取ini文件的数据。
     2.1 引入ConfigParse类
     2.2  实例化ConfigParse类,调用read方法,读取ini文件
            conf = ConfigParser()
            conf.read(file,encoding=”utf-8”)
            设置语言格式为utf-8方便阅读 不涉及转码
     
    2.3 读取
        1、读取出来默认是字符串
         conf.get(section名字,option名字)
        2、支持读取出来为:bool,int,float
              conf.getboolean(section,option)
              conf.getint(section,option)
              conf.getfloat(section,option)
 
   写入配置文件(了解)
       1、在已有section下添加/修改 option和value
         conf.set(section,option,value)
        2、将1中的变更写入到配置文件当中。
             conf.write(open(文件,“w”,encoding=”utf-8”))
        3、若要新增section:
             conf.add_section(section名字)

"""
from  configparser import ConfigParser
# 导入configparser模块 实例化并写入文件和语言格式
conf = ConfigParser()
conf.read('mysql.ini',encoding="utf-8")

host = conf.get("mysql","host")
port = conf.getint("mysql","port")
# 在已有section下添加/修改 option和value
conf.set("mysql","ppp","000")
conf.write(open('mysql','w',encoding='utf-8'))
# 将修改后的文件保存 保存后会产生一个新的文件

ppp = conf.get("mysql","ppp")
print(host)
print(port)

数据库参数化登录

import  pymysql
from configparser import ConfigParser
class my_sql:
    def __init__(self):
        conf = ConfigParser()
        conf.read("mysql.ini", encoding="utf-8")
        # 导入configparser模块 实例化并写入文件和语言格式
        # 直接通过导入configparser模块的get方法获取  因为端口是int格式 因此使用getint方法
        try:
           self.con = pymysql.connect(
                host=conf.get("mysql","host"),
                database=conf.get("mysql","database"),
                port=conf.getint("mysql","port"),
                user=conf.get("mysql","user"),
                password=conf.get("mysql","passwd"),
                cursorclass=pymysql.cursors.DictCursor  # 一行数据是字典形式。多行数据是列表中嵌套字典.
            )
        except :
            raise
        # 如果有异常  会通过raise抛出
        else:
            # 建立游标
            self.cur = self.con.cursor()

    def get_count_query(self,select_sql,args=None):
        count =self.cur.execute(select_sql,args)
        return  count

    def get_quert_sql_result(self,select_sql,args=None,size=1):
        """
        :param select_sql:
        :param args:
        :param size: size = 1表示fetchone size = -1表示fetchall size>1表示fetchmany
        :return:
        """
        self.cur.execute(select_sql,args)
        if size == 1 :
            return self.cur.fetchone()
        elif size == -1 :
            return self.cur.fetchall()
        elif size >1:
            return self.cur.fetchmany(size)


    def update_sql(self,update_sql,args=None):
        try:
            self.cur.execute(update_sql,args)
        except :
            self.con.rollback()
        else:
            self.con.commit()
    def colse(self):
        self.cur.close()
        self.con.close()


if __name__ == '__main__':

  mysql = my_sql()
  res = mysql.get_quert_sql_result('SELECT  * FROM member WHERE mobile_phone="12345678900";')
  #调用查询方法来查数据
  print(res)
  mysql.update_sql('UPDATE member SET leave_amount=1314 WHERE mobile_phone="12345678900";')
    #调用更新方法来修改数据
  res = mysql.get_quert_sql_result('SELECT  leave_amount FROM member WHERE mobile_phone="12345678900";')
    #调用查询方法来查数据 是否已经完成更新
  print(res)
  mysql.colse()
  # 关闭连接池 释放资源

MySQL.ini配置如下
[mysql]
host127.0.0.1
database=root
user=root
passwd=123456
port=3306
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值