建立以类开进行编程的思维,这是很多刚开始接触开发的人所缺少的,比如我们对一些公用的操作
可以放到一个类是来进行处理
import pymysql
import logging
logging.basicConfig(level=logging.INFO,format="%(asctime)s-%(levelname)s:%(message)s")
class MysqlUtils():
# database operation class
def __init__(self,dict):
#__init__ function
self.dict=dict
def get_conn(self):
##get database conneciton
try:
self.conn = pymysql.connect\
(host=self.dict["host"],
port=self.dict["port"],
user=self.dict["user"],
password=self.dict["password"],
charset=self.dict["charset"])
logging.debug("database connection get sucessfull:" )
except Exception as e:
logging.info("database connection get error:"+e.args[1])
def close_conn(self):
#close connection
try:
self.conn.close()
logging.debug("database connection close sucessfull!")
except Exception as e:
logging.info("database connection close error:" + e.args[1])
def get_all(self,sql):
#execute query
try:
self.cur=self.conn.cursor()
self.cur.execute(sql)
logging.debug("database cursor close error:" )
return self.cur.fetchall()
except Exception as e:
self.cur.close()
logging.info("database cursor close error:" + e.args[1])
def execute(self,sql):
#execute dml
try:
self.cur = self.conn.cursor()
self.cur.execute(sql)
logging.debug("database cursor close error:")
return 1
except Exception as e:
self.cur.close()
logging.info("database cursor close error:" + e.args[1])
return 0
def main():
dict={"host":"192.168.56.156","port":3306,"user":"root","password":"pwd","charset":"utf8"}
mysqlUtils=MysqlUtils(dict)
mysqlUtils.get_conn()
logging.info(mysqlUtils.get_all("select version()").__str__())
mysqlUtils.close_conn()
if __name__=="__main__":
main()