标签:sql数据库 mysq char 操作 rom file 查询语句 hand close
python中要操作数据库,要使用该数据库在python中对应的驱动库,本文介绍python操作mysql数据库
1.首先安装pymysql
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)
标签:sql数据库 mysq char 操作 rom file 查询语句 hand close
原文地址:https://www.cnblogs.com/hherbk/p/12746184.html