我创建的查询数据库的类是这样的
class MySQLQuery():
def __init__(self, ip, username, password, database):
'''
初始化 MySQL 数据库
'''
self.__sql = pymysql.connect(host=ip, user=username, password=password, db=database)
self.__cursor = self.__sql.cursor()
def selectOneResult(self, sentence):
'''
返回的结果是一个 tuple
如果不存在,返回结果是个 NoneType
'''
self.__cursor.execute(sentence)
result = self.__cursor.fetchone()
return result
初始化数据库连接是这样的
from lib.util.MySQLQuery import MySQLQuery
controllerDB = MySQLQuery(ip=MySQLIP, username=MySQLUserName, password=MySQLPassWord,
database='cloudplayer_controller_hometest')
使用这个的是另一个文件,使用的部分是这样的
from lib.util.GlobalVariable import controllerDB
def a():
# 做了一些事情...
while True:
sqlSentence = 'select instance_id from service where id = {selectid}'.format(selectid=selectID)
instanceID = controllerDB.selectOneResult(sqlSentence)[0]
newSqlSentence = 'select status from instance_status where instance_id = {instanceid}'.format(instanceid=instanceID)
status = controllerDB.selectOneResult(newSqlSentence)[0]
if status == 'WORKING':
break
time.sleep(3)