一直都想好好的学习Python,但是一直都没有如愿。这两天要做个小程序,就想到使用Python来处理,结果这几天的进步比以往总和都要大。学习语言还是要从实践中来做了。一直想做个Python连接PostgreSQL数据库的Manager,做个开源的项目来增进对这两个产品的学习。把代码贴出来,使用Python连接PostgreSQL数据库的第二篇:
from mx.DateTime import *
import pg
import random
def insertdb(id, initNum):
nrange = range(initNum - 15, initNum +20)
marchbegin = Date(2005, 3, 1)
marchend = Date(2005, 4, 1)
i = 10
insertstrlist = []
while True:
intever = marchbegin + RelativeDateTime(day=1,hour=0,minute=i,second=0)
n = random.choice(nrange)
sql = "INSERT INTO srdata (\"srid\", \"srdtime\", \"srdcount\", \"srdstat\") VALUES ('" + str(id) + "', '" + str(intever) + "', '" + str(n) + "', '" + str(initNum) +"')"
insertstrlist.append(sql)
if marchend == intever :
break
i = i + 10
return insertstrlist
region50list = {'1':1120, '2':1222, '3': 1103, '4': 902}
region64list = {'5':1000, '6':1200, '7': 973, '8': 823}
region73list = {'9':1020, '10':1287, '11': 1122, '12': 1244}
db = pg.connect(dbname = 'stat', host = '192.168.0.2', user = 'bbs', passwd = '2037423')
for region in db.query("SELECT * FROM sregions").dictresult():
if (region["srid"] < 5):
num = region50list[str(region["srid"])]
sql50 = insertdb(region["srid"], num)
for i in sql50:
db.query(i)
print "Insert OK : " + i
if (region["srid"] > 5 and region["srid"] < 9):
num = region64list[str(region["srid"])]
sql64 = insertdb(region["srid"], num)
for i in sql64:
db.query(i)
print "Insert OK : " + i
if (region["srid"] > 8 and region["srid"] < 13):
num = region73list[str(region["srid"])]
sql70 = insertdb(region["srid"], num)
for i in sql70:
db.query(i)
print "Insert OK : " + i