摘自python帮助文档

一、基本用法

import sqlite3
conn = sqlite3.connect('example.db')
#conn = sqlite3.connect(':memory:') c
= conn.cursor() c.execute('''CREATE TABLE stocks (date text, trans text, symbol text, qty real, price real)''') #NULL,INTEGER,REAL,TEXT,BLOB
c.execute(
"INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)") conn.commit() conn.close()

二、查询

c.excute('select * from stocks')

a=c.fetchone()
while a: #a!=None
  print a
  a=c.fetchone()

a=c.fetchmany() #(size=n),default cursor.arraysize,default 1
while a:
for row in a:
print row
a=c.fetchmany()

a
=c.fetchall() for row in a: print row for row in c.execute('select * from stocks'): print row

print c.description

三、参数 

c.execute('select ?',(123,))
c.fetchone()

t = ('RHAT',) c.execute('SELECT * FROM stocks WHERE symbol=?', t) print c.fetchone()
# This is the qmark style:
cur.execute("insert into people values (?, ?)", (who, age))
# And this is the named style:
cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})
# Larger example that inserts many records at a time
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
             ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
             ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
            ]
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
print c.rowcount

 四、row_factory

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

con = sqlite3.connect(":memory:")
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print cur.fetchone()["a"]


>>> conn.row_factory = sqlite3.Row
>>> c = conn.cursor()
>>> c.execute('select * from stocks')
<sqlite3.Cursor object at 0x7f4e7dd8fa80>
>>> r = c.fetchone()
>>> type(r)
<type 'sqlite3.Row'>
>>> r
(u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.14)
>>> len(r)
5
>>> r[2]
u'RHAT'
>>> r.keys()
['date', 'trans', 'symbol', 'qty', 'price']
>>> r['qty']
100.0

五、connect.create_function, create_aggregate, create_collation

六、object adapter
build-in adapter:datetime.datetime, datetime.date

 

posted on 2013-12-08 23:25  perel  阅读(388)  评论(0编辑  收藏  举报