今天看了下如何连接mysql并执行命令。想了下,最好是封装一下,以后经常会用,也会方便很多。
然后随便写了个简单的mysqlhelper。
import pymysql.cursors as pymy import pymysql class MySqlHp: def __init__(self,host,uid,pwd,database,tableName): config={ 'host':host, 'port':3306, 'user':uid, 'password':pwd, 'db':database, 'charset':'utf8mb4', 'cursorclass':pymy.DictCursor,} self.connect=pymysql.connect(**config) self.tableName=tableName #执行指定sql语句 def exec(self,sql): try: with self.connect as cursor: cursor.execute(sql) self.connect.commit() finally: self.connect.close() #执行sql查询语句 def get(self,sql): try: with self.connect as cursor: cursor.execute(sql) result=cursor.fetchone() self.connect.commit() finally: self.connect.close() return result #根据id删除指定数据 def delByID(self,id): try: with self.connect as cursor: sql="delete from {} where id={}".format(self.tableName,id) cursor.execute(sql) self.connect.commit() finally: self.connect.close() #根据id获取指定数据 def getByID(self,id): try: with self.connect as cursor: sql = "select * from {} where id ={}".format(self.tableName, id) cursor.execute(sql) result=cursor.fetchone() self.connect.commit() finally: self.connect.close() return result