`
xiagu1
  • 浏览: 47492 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

python数据库应用

阅读更多

最近用的比较多的数据库是sqlite,本身我机器上装的activepython,自带有sqlite3,我自己写的存储数据的代码如下:

def store_data(id_name,sq_data):
    """将获取到的数据比较并插入到sqlite"""
    #连接数据库
    cx = sqlite.connect('chaojiv1.1.sqlite')
    cu = cx.cursor()
    #raw_input("Press ENTER to exit")
    #0,1、2、3、4别为min/max/mostnum/mostprice/price/
    cu.execute('''create table if not exists kaixin(
        id text primary key,
        name text,
        min float,
        max float,
        mostpricenum text,
        mostprice float,
        price float,
        rate float,
        maxrate float,
        categ text
        )''')
    #查询比较并写入数据库
    #rc='replace into  kaixin values(' +pp[jj]+',"'+bb[jj]+'",'+xmlprice[-1]+','+max(xmlprice)+','+min(xmlprice)+')'
    for i in id_name[0].keys():
        rc='select min, max, mostpricenum,mostprice from kaixin where id='+i
        #mostprice float, mostpricenum text, maxrate float
        cu.execute(rc)
        oo=cu.fetchall()
        #c为tuple,0,1、2、3、4别为min/max/mostnum/mostprice/price/
        temp0=sq_data[0][i]
        temp1=sq_data[1][i]
        temp2=sq_data[2][i]
        temp3=sq_data[3][i]
        temp4=sq_data[4][i]
        if len(oo)==0:
            print "new item",id_name[0][i].decode('utf-8').encode('gbk')
        else:
            if temp0>oo[0][0]:
                temp0=oo[0][0]
            if temp1<oo[0][1]:
                temp1=oo[0][1]
            if temp2<oo[0][2]:#比较多出现的价格次数,次数少就按照多出现的价格
                temp2=oo[0][2]
                temp3=oo[0][3]
    #print rc
        rc='replace into  kaixin values(' +i+',"'+id_name[0][i]+'",'+str(temp0)+','+str(temp1)+ \
          ','+str(temp2)+','+str(temp3)+',' +str(temp4)+','+str((float(temp1)-float(temp4))/float(temp4)*100)+\
          ','+ str((float(temp3)-float(temp4))/float(temp4)*100)+',"'+id_name[1][i] + '")'
        #print rc
        cu.execute(rc)
    cx.commit()
    cx.close()

 同样的,python支持各种类型的数据库,而且只要相应的库遵循python的DB API,那么连接方式大同小异。比如SQLSERVER的使用。首先安装pymssql,地址在:http://pymssql.sourceforge.net/

然后就跟使用sqlite很类似了。

import os
import  sys
import  string
import pymssql as sqlite1

# 连接数据库
try:
    cx = sqlite1.connect(host='172.18.1.1',user='user',password='pass',database='elementinfo')
    print "connect ok"
except Exception, e:
    print e
    print "erro"
    sys.exit()
# 获取cursor对象来进行操作
cu = cx.cursor()
#查询出数据
sql = "select * from tabTimeData where ObservTimes<2009031008 and ObservTimes>2009031000"
print sql
cu.execute(sql)
raw_input("Press ENTER to exit")
alldata = cu.fetchall()
if alldata:
    for rec in alldata:
        print rec
cu.close()
cx.close()
print type(alldata)
print len(alldata)
print alldata[3][3]
print "end"
 

 

 

0
0
分享到:
评论
1 楼 cloverprince 2010-04-22  
另外,python有没有支持sql语句的构造呢?比如类似这样:
stu_name = """John Smith';drop table students......"""
make_statement("select * from students where name = ?", stu_name)

防止注入。

相关推荐

Global site tag (gtag.js) - Google Analytics