python中操作数据库

zhuquan0 2020-04-21

python中要操作数据库,要使用该数据库在python中对应的驱动库,本文介绍python操作mysql数据库

1.首先安装pymysql

python中操作数据库

 2.导入库

3.建立连接

4.建立游标

5.发起请求

6.得到结果

7.关闭游标、连接

import pymysql
import yaml
from pymysql.cursors import DictCursor

from config.setting import conf


class DBhandler():
    def __init__(self,host,user,password,port,charset,
                 database=None,cursorclass=DictCursor,**kw):
        """初始化"""
        #建立连接
        #建立游标
        self.conn=pymysql.connect(host=host,user=user,
                                  password=password,port=port,
                                  charset=charset,database=database,
                                  cursorclass=cursorclass,**kw)
        self.curs=self.conn.cursor()

    def query(self,sql,args=None,one=True):
        """查询语句"""
        self.curs.execute(sql,args)
        # 获取结果
        if one:
            return  self.curs.fetchone()
        else:
            return self.curs.fetchall()

    def close_db(self):
        """关闭连接"""
        self.curs.close()
        self.conn.close()

if __name__ == ‘__main__‘:
    with open(conf.yaml_file_path,encoding=‘utf8‘)as f:
        yaml_data=yaml.load(f,Loader=(yaml.FullLoader))
        print(yaml_data)
        db=DBhandler(host=yaml_data["DBhandler"]["host"],
                     user=yaml_data["DBhandler"]["user"],
                     password=yaml_data["DBhandler"]["password"],
                     port=yaml_data["DBhandler"]["port"],
                     charset=yaml_data["DBhandler"]["charset"],
                     database=yaml_data["DBhandler"]["database"])
    res = db.query("select * from member limit 2;")
    print(res)

相关推荐