python中操作数据库
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)
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16