SQLite数据库是一款非常小巧的嵌入式开源数据库软件
创建在硬盘上面: conn = sqlite3.connect('test.db')
创建在内存上面: conn = sqlite3.connect('"memory:')
其中conn对象是数据库链接对象,而对于数据库链接对象来说,具有以下操作:
commit() --事务提交
rollback() --事务回滚
close() --关闭一个数据库链接
cursor() --创建一个游标
c= conn.cursor(),这样我们就创建了一个游标对象:c,在sqlite3中,所有sql语句的执行都要在游标对象的参与下完成
对于游标对象c,具有以下具体操作:
execute() --执行一条sql语句
executemany() --执行多条sql语句
close() --游标关闭
fetchone() --从结果中取出一条记录
fetchmany() --从结果中取出多条记录
fetchall() --从结果中取出所有记录
scroll() --游标滚动
# coding: utf-8
import sqlite3
#创建表
def createTable():
conn=sqlite3.connect('test.db')
c=conn.cursor()
#创建表
c.execute('''create table user
(id int primary key,name text,title text)
''')
conn.commit()
conn.close()
#添加数据
def createDate():
conn=sqlite3.connect('test.db')
c=conn.cursor()
sql=[(1,'kenny','the book is very good'),
(2,'tom','you are a good man'),
(3,'mary','i love your mary')
]
c.executemany('insert into user values (?,?,?)',sql)
conn.commit()
conn.close()
#查询数据
def query():
conn=sqlite3.connect('test.db')
c=conn.cursor()
c.execute('select * from user')
#一条条查询
#print c.fetchone()
#print c.fetchone()
#print c.fetchone()
#print c.fetchall()
for row in c.execute('select name,title from user'):
print row
#更新数据
def update():
conn=sqlite3.connect('test.db')
c=conn.cursor()
c.execute('update user set name=?,title=? where id=?',('jarry','jarry find a good job',2))
conn.commit()
conn.close()
if __name__=='__main__':
#createTable()
#createDate()
update()
print '-------------'
query()