1 获取行数
fp = open("db.config", "r")
data = fp.read()
fp.close()
datas = json.loads(data)
# 连接数据库
db = MySQLdb.connect(datas['url'], datas['username'], datas['password'], datas['dbname'], charset='utf8')
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 构造表名称
# cdro_2018_4_9
nowtime = datetime.datetime.now().timetuple()
table_name = 'cdro_' + str(nowtime.tm_year) + '_' + str(nowtime.tm_mon) + '_' + str(nowtime.tm_mday)
logging.debug("------------------开始获取%s的业务并发,应答率,接通率", table_name)
# 十分钟之前的时间
lastTenMinuteTime = time.time() - 60*10
lastTenMinuteTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(lastTenMinuteTime))
# 当前时间
nowTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# 并发
concurrentSql = ' SELECT count(*) AS total FROM ' + table_name + ' WHERE calldate >= ' + lastTenMinuteTime + \
' AND calldate <='+nowTime
cursor.execute(concurrentSql)
concurrentNum = cursor.fetchone()[0]
2 查询数据并且转json数组
# 连接数据库
db = MySQLdb.connect(datas['url'], datas['username'], datas['password'], datas['dbname'], charset='utf8')
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 并发
sql = "SELECT * AS total FROM user "
cursor.execute(sql)
rows = cursor.fetchall()
data=[]
for row in rows:
obj={}
obj['id']=row[0]
obj['name']=row[1]
obj['password']=row[2]
data.append(obj)
return json.dumps(data)