这两天主要实现了之前预想的一个功能,MySQLReader,主要用于读取数据库的数据。因为主要用于接口测试,所以这个类只实现了简单的查询功能。这个功能实现不算复杂,如果需要自己搭建MySQL服务器的话那就另说了。
py27
class MySQLClient(object):
def __init__(self, localhost, username, password, db_name):
self.localhost = localhost
self.username = username
self.password = password
self.db_name = db_name
self.db = self.connected_db()
def __repr__(self):
return self.localhost, self.username, self.password, self.db_name
def connected_db(self):
try:
db = MySQLdb.connect(self.localhost, self.username, self.password, self.db_name, charset='utf8' )
except _mysql_exceptions.OperationalError as e:
print u'数据库连接失败!'
print repr(e)
sys.exit()
return db
def disconnected_db(self):
self.db.close()
def select(self, table, where, search):
'''
:param table: 需要查询的表名 eg: Account
:param where: 条件语句 eg: name = 'XiaoMing' and sex = '0'
:param search: 需要查询的字段 eg: ['accountId', 'address']
:return: eg: {'accountId': [accountId1, accountId2], 'address': [address1, address2]}
'''
result = {}
self.cursor = self.db.cursor()
sql_search = ','.join(search)
sql = 'select %s from %s where %s;' % (sql_search, table, where)
try:
self.cursor.execute(sql)
except _mysql_exceptions.ProgrammingError as e:
print u'SQL 语句编写异常,请检查参数是否正确'
print repr(e)
sys.exit()
search_data = self.cursor.fetchall()
for i in range(len(search)):
result[search[i]] = []
for j in search_data:
result[search[i]].append(j[i])
self.cursor.close()
self.db.commit()
return result
之后有空的话自己搭建MySQL数据库服务端,然后用Flask搭建API服务器。
回家以后用py3重写了一遍,这次用的是pymysql模块,不过返回值稍微有一点变化。
py3.6.5
# coding=utf-8
import pymysql
import sys
class MySQLClient(object):
def __init__(self, host, user, password, db_name):
self.host = host
self.user = user
self.password = password
self.db_name = db_name
self.connection = self.connected_db()
self.cursor = self.connection.cursor()
def connected_db(self):
try:
connection = pymysql.connect(host=self.host,
user=self.user,
password=self.password,
db=self.db_name,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
except pymysql.err.OperationalError as e:
print('数据库连接失败!')
print(repr(e))
sys.exit()
return connection
def disconnected_db(self):
self.connection.close()
def select(self, table, where, search):
'''''
:param table: 需要查询的表名 eg: Account
:param where: 条件语句 eg: name = 'XiaoMing' and sex = '0'
:param search: 需要查询的字段 eg: ['accountId', 'address']
:return: eg: [{'name': 'sam', 'sex': 'boy'}, {'name': 'tom', 'sex': 'boy'}]
'''
sql_search = ','.join(search)
sql = 'select %s from %s where %s;' % (sql_search, table, where)
try:
self.cursor.execute(sql)
except pymysql.err.ProgrammingError as e:
print('SQL 语句编写异常,请检查参数是否正确')
print(repr(e))
print('sql:%s' % sql)
sys.exit()
search_data = self.cursor.fetchall()
return search_data
if __name__ == '__main__':
db = MySQLClient(host='localhost', user='test', password='123456', db_name='test_db')
result = db.select(table='account', where='id=1', search=['name', 'sex'])
print(result)