1,数据库连接对象的创建
con = sqlite.connect("mydbs.db")
con有以下几个常用的属性:
commit():提交一个事物
close():关闭数据库连接
rollback():回滚一个事物
cursor():创建一个游标对象
2,游标对象
所有的SQL执行语句都是在游标对象下进行的。
cur=con.cursor()
游标对象有以下操作:
execute(): 执行一条语句
executemany():执行多条语句
fetchone(): 从结果中获取一条记录
fetchmany(): 从结果中获取多条记录
fetchall(): 从结果中获取全部的记录
scroll(): 游标回滚
close():关闭游标
注:
1,对数据库修改的语句都要执行commit()语句;
2,游标是有状态的,它记录当前已经取到结果的第几个记录了;
举例:
“`
from pysqlite2 import dbapi2 as sqlite
con = sqlite.connect(“mydbs.db”)
con.execute(“create table students(id,name,age,sex)”)
cur=con.cursor()
cur.execute(“insert into students values(1,’jinduo’,24,’girl’)”)
cur.execute(“insert into students values(2,’xiaoru’,23,’girl’)”)
cur.execute(“insert into students values(3,’jiajia’,23,’girl’)”)
cur.execute(“insert into students values(4,’yujia’,24,’girl’)”)
con.commit()
cur.execute(“select * from students”)
list = cur.fetchmany()“`