sqlite读写
#coding=utf-8 import sqlite3 import os #创建数据库和游标 if os.path.exists(' test.db'):conn=sqlite3.connect(' test.db')cur=conn.cursor() else:conn=sqlite3.connect(' test.db')cur=conn.cursor()#创建表 cur.execute('CREATE TABLE IF NOT EXISTS customer (ID VARCHAR(300),NAME VARCHAR(300),''SEX VARCHAR(300),TELEPHONE VARCHAR(300),PRIMARY KEY(ID))') try:#插入数据for t in [('1','alex','man','189'),('2','tom','man','139')]:conn.execute('INSERT INTO customer VALUES(?,?,?,?)',t)#未出错commit提交后生效conn.commit() except:#出错,回滚conn.rollback() #关闭游标 cur.close() #关闭数据库链接 conn.close()
使用游标查询数据库:
游标对象有以下的操作:
execute()--执行sql语句
executemany--执行多条sql语句
close()--关闭游标
fetchone()--从结果中取一条记录,并将游标指向下一条记录
fetchmany()--从结果中取多条记录
fetchall()--从结果中取出所有记录
scroll()--游标滚动
1.查询
cur.execute("select * from customer")
cur. fetchall()
2.修改
cur.execute("update customer set sex='women' where id = 1")
cx.commit()
3.删除
cur.execute("delete from customer where id = 1")
conn.commit()
4.打印中文,须依次打印字符串
for item in cur.fetchall():
for element in item:
print element
参考:
http://www.cnblogs.com/yuxc/archive/2011/08/18/2143606.html
http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001388320596292f925f46d56ef4c80a1c9d8e47e2d5711000