@lingdantiancai
2016-04-21T15:59:13.000000Z
字数 1655
阅读 1922
未分类
---以下文章大部分各种复制剪切来的是[这个网址][1]
创建并打开数据库
import sqlite3
conn = sqlite3.connect('example.db')
如果指定的数据库存在,就会直接打开这个数据库,否则将新建一再打开。
也可以提供专用名 :memory: 来在内存中建立数据库。
数据库连接对象
旦拥有了连接(Connection)对象,就可以创建游标(Cursor)对象并调用他的execute()方法来执行SQL语句:
c = conn.cursor()
#Create table
c.execute('''CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)''')
#Insert a row of data
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
#Save (commit) the changes
conn.commit()
#We can also close the connection if we are done with it.
#Just be sure any changes have been committed or they will be lost.
conn.close() `
c.execute("create table catalog (id integer primary key,pid integer,name varchar(10) UNIQUE,nickname text NULL)")
上面语句创建了一个叫catalog的表,它有一个主键id,一个pid,和一个name,name是不可以重复的,以及一个nickname默认为NULL。
c.execute("drop table catalog")
上面语句将catalog表删除。
另外SQLite中没有清空表的操作,使用如下方式替代:
c.execute("delete from catalog")
通常SQL语句中会用到python变量作为值(value)。不建议直接使用python的字符串运算来构造查询语句,因为这样是不安全的,会使你的程序容易受到SQL注入攻击。
可以使用DB-API提供的参数代换。在想使用值(value)的地方放置一个'?'作为占位符,然后提供一个由值(value)组成的元组作为游标(cursor)中execute()方法的第二个参数。(其他的数据库模块可能使用别的占位符,比如 '%s' 或者 ':1')
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)
c.execute("UPDATE catalog SET trans='SELL' WHERE symbol = 'IBM'")
正如前面所说,提倡使用元组进行操作。
#never do this
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print c.fetchone()
t=('RHAT')
c.execute("DELETE * FROM stocks WHERE symbol=?", t)
`