python提取数据库数据_一段python从mysql数据库中取数据并且求平均值的代码

#encoding=gbk

import sys

import MySQLdb

import datetime

import time

dict = {"0":"0-0","1" : "0-500","2" : "500-700","3" : "700-900","4" : "900-1200",

"5" : "1200-1600","6" : "1600-2000","7" : "2000-2500","8" : "2500-3000",

"9" : "3000-3500","10" : "3500-4000","11" : "4000-5000","12" : "5000-7000",

"13" : "7000-10000","14" : "10000-14999","15" : "15000-19999",

"16" : "20000-29999","17" : "30000-49999",

"18" : "50000-100000","19" : "100000-100000",}

city=["合肥","芜湖","蚌埠","六安","安庆",

"淮南","马鞍山","淮北","铜陵","黄山",

"滁州","阜阳","宿州","亳州","池州",

"宣城"]

def getvalue(x):

list=dict[x].split('-') #['0', '500']

return list

#计算时间

starttime = datetime.datetime.now()

conn=MySQLdb.Connection('127.0.0.1','root','123456','job',charset='gbk')

cur=conn.cursor()

#循环输出所有城市

for ci in city:

#去除空数据 & 面议数据 & 工作地点为空数据

count=cur.execute("SELECT etjobsalary FROM demo_jobs_store\

WHERE etjoblocation_str LIKE '%%%s%%'"%ci)

conn.commit()

print "总记录:%s" %count

#执行检查结果

cur.scroll(0,mode='absolute')

results=cur.fetchall()

fields=cur.description

low=0

high=0

i=0

for ics in range(0,len(results)):

a=int(getvalue(results[ics-1][0])[0])

b=int(getvalue(results[ics-1][0])[1])

if a<100000 and b<100000:

low+=a

high+=b

print "%s的工资是:"%ci

print int((low/count)*0.01)*100

print int((high/count)*0.01)*100

#时间结束

endtime = datetime.datetime.now()

#输出时间

print (endtime - starttime).seconds

代码解释:

1、需要安装mysqldb for python的插件

2、该段代码的主要作用是从mysql数据库中字段取出数据,并且根据字段对应的值来取平均值

数据库截图:

http___img0.tuicool.com_ea2Uze.jpg

结果输出如图:

http___img1.tuicool.com_YrU7Nz.jpg

总结:

1、该段代码用到了多种结构,例如list和dict等。

2、用到了函数。

3、用到了mysql的循环处理。

4、统计程序运行时间。

文章来自乐职网  http://www.lezhi.com/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值