In [1]:
import os
In [2]:
db_file = "example.db"
if os.path.exists(db_file):
    os.remove(db_file)
In [3]:
import sqlite3
In [4]:
con = sqlite3.connect(db_file)
In [6]:
cursor = con.cursor()
In [7]:
cursor.execute('''CREATE TABLE stocks
          (date text, trans text, symbol text, qty real, price real)''')
Out[7]:
<sqlite3.Cursor at 0x7f3d29f70ea0>
In [9]:
cursor.execute("""INSERT INTO stocks VALUES 
          ('2006-01-05','BUY','RHAT',100,35.14)""")
Out[9]:
<sqlite3.Cursor at 0x7f3d29f70ea0>
In [12]:
cursor.execute("""INSERT INTO stocks VALUES 
          ('2006-02-05','BUY','FED',200,35.24)""")
Out[12]:
<sqlite3.Cursor at 0x7f3d29f70ea0>
In [13]:
for item in cursor.execute("select * from stocks"): # 直接用循环遍历查询结果
    print(item)
('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
('2006-02-05', 'BUY', 'FED', 200.0, 35.24)
In [14]:
# Never do this -- insecure!
# symbol = 'RHAT'
# cursor.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)

# Do this instead
t = ('RHAT',)
cursor.execute('SELECT * FROM stocks WHERE symbol=?', t) # 使用内置的替换,减少安全风险
print(cursor.fetchone())
('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
In [15]:
# 使用executemany执行多条操作
# 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),
            ]
cursor.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
Out[15]:
<sqlite3.Cursor at 0x7f3d29f70ea0>
In [16]:
# 执行脚本
sql = """create table news (id integer, score integer, title text, href text);
insert into news values (1, 8, "hello world", "http://oscar-lab.org");
insert into news values (2, 2, "hello charlie", "http://www.dlut.edu.cn");""" # sql语句间要用分号分隔
cursor.executescript(sql)
Out[16]:
<sqlite3.Cursor at 0x7f3d29f70ea0>
In [17]:
print(list(cursor.execute("select * from news")))
[(1, 8, 'hello world', 'http://oscar-lab.org'), (2, 2, 'hello charlie', 'http://www.dlut.edu.cn')]
In [19]:
con.row_factory = sqlite3.Row
c = con.cursor()
c.execute('select * from stocks')
Out[19]:
<sqlite3.Cursor at 0x7f3d29f72420>
In [20]:
r = c.fetchone()
In [21]:
type(r)
Out[21]:
sqlite3.Row
In [22]:
r.keys()
Out[22]:
['date', 'trans', 'symbol', 'qty', 'price']
In [23]:
r['date']
Out[23]:
'2006-01-05'
In [24]:
for field in r:
    print(field)
2006-01-05
BUY
RHAT
100.0
35.14
In [25]:
con.close()
In [ ]: