介绍
这是通过对pymysql进行的二次简单封装,封装后可以很方便地调用以对mysql数据库进行操作。
引用方式:在要使用数据库的地方import该对象,然后通过AmanMySQL(mysql[“host”], mysql[“user”], mysql[“passwd”], mysql[“dbName”])连接数据库赋值给某一变量,之后就可以通过对应变量对select、update、insert、delete等对数据库做操作。源码和示例如下:
源码
#encoding: utf-8
import pymysql
class AmanMySQL():
# 初始化
def __init__(self, host, user, passwd, dbName):
self.host = host
self.user = user
self.passwd = passwd
self.dbName = dbName
# 连接数据库,需要传数据库地址、用户名、密码、数据库名称,默认设置了编码信息
def connet(self):
try:
self.db = pymysql.connect(self.host, self.user, self.passwd, self.dbName, use_unicode=True, charset='utf8')
self.cursor = self.db.cursor()
except Exception as e:
return e
# 关闭数据库连接
def close(self):
try:
self.cursor.close()
self.db.close()
except Exception as e:
return e
# 查询操作,查询单条数据
def get_one(self, sql):
# res = None
try:
self.connet()
self.cursor.execute(sql)
res = self.cursor.fetchone()
self.close()
except Exception:
res = None
return res
# 查询操作,查询多条数据
def get_all(self, sql):
# res = ()
try:
self.connet()
self.cursor.execute(sql)
res = self.cursor.fetchall()
self.close()
except Exception:
res = ()
return res
# 查询数据库对象
def get_all_obj(self, sql, tableName, *args):
resList = []
fieldsList = []
try:
if (len(args) > 0):
for item in args:
fieldsList.append(item)
else:
fieldsSql = "select COLUMN_NAME from information_schema.COLUMNS where table_name = '%s' and table_schema = '%s'" % (
tableName, self.dbName)
fields = self.get_all(fieldsSql)
for item in fields:
fieldsList.append(item[0