import mysql.connector
class MySqlHelper(object):
"""操作数据库帮助类"""
def __init__(self):
self.host = "192.168.0.150"
self.user = "root"
self.password = "root"
self.database = "sys_database"
try:
self.mydb = mysql.connector.connect(host=self.host,
user=self.user,
passwd=self.password,
database=self.database,
connect_timeout=10))
self.mycursor = self.mydb.cursor()
except Exception as e:
print('MySql Error : %d %s' % (e.args[0],e.args[1]))
#不带参数的查询
def select(self,mysql):
try:
self.mycursor.execute(mysql)
values = self.mycursor.fetchall()
return values
except Exception as e:
print ('select Error : %d %s' % (e.args[0],e.args[1]))
return []
finally:
self.mycursor.close()
self.mydb.close()
#带参数的查询
def select2(self,mysql,na):
try:
self.mycursor.execute(mysql,na)
values = self.mycursor.fetchall()
return values
except Exception as e:
print ('select2 Error : %d %s' % (e.args[0],e.args[1]))
return []
finally:
self.mycursor.close()
self.mydb.close()
#更新
def Update(self,mysql,na):
try:
self.mycursor.execute(mysql,na)
self.mydb.commit()
row = self.mycursor.rowcount
if row > 0:
return True
else:
return False
except Exception as e:
print ('Update Error : %d %s' % (e.args[0],e.args[1]))
return False
finally:
self.mycursor.close()
self.mydb.close()
#插入数据
def Insert(self,mysql,na):
try:
self.mycursor.execute(mysql,na)
self.mydb.commit()
row = self.mycursor.rowcount
if row > 0:
return True
else:
return False
except Exception as e:
print('Insert Error : %d %s' % (e.args[0],e.args[1]))
return False
finally:
self.mycursor.close()
self.mydb.close()
使用数据:
from DAL import MySqlHelper
from Entity import TaskPoolEntity
import datetime
class TaskPoolDAL(object):
"""操作数据库t_du_task"""
sqlHelper = MySqlHelper.MySqlHelper()
#查询所有的任务
def selectTasks():
TaskPoolDAL.sqlHelper = MySqlHelper.MySqlHelper()
sql='select * from t_dutask'
values= TaskPoolDAL.sqlHelper.select(sql)
data=[]
for item in values:
selectTask = TaskPoolEntity.TaskPoolEntity(item)
data.append(selectTask)
return data