#coding=utf-8import sqlite3import 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参考: