Python Sqlite3数据库相关操作


1、连接数据库:

cx= sqlite3.connect(‘database.db’) ,cx是一个数据库连接对象,它有以下操作:

commit()--事务提交

rollback()--事务回滚

close()--关闭一个数据库连接

cursor()--创建一个游标

 


2、获得游标对象:

所有sql语句都要在游标对象下执行,用cu= cx.cursor()来定义了一个游标,游标对象有以下的操作:

execute()--执行sql语句

executemany--执行多条sql语句

close()--关闭游标

fetchone()--从结果中取一条记录

fetchmany()--从结果中取多条记录

fetchall()--从结果中取出多条记录

scroll()--游标滚动

 


3、sqlite3使用举例:

3.1、建表

cu.execute("""createtable catalog (

idinteger primary key,

pidinteger,

namevarchar(10) UNIQUE)""")

上面语句创建了一个叫catalog的表,它有一个主键id,一个pid,和一个name,name是不可以重复的。

3.2、insert(插入)数据

>>>cu.execute("insert into catalog values(?,?,?)",(0, 0,'name1'))

>>>cu.execute("insert into catalog values(1, 0, 'hello')")

>>>cx.commit()

如果你愿意,你可以一直使用cu游标对象。注意,对数据的修改必须要使用事务语句:commit()或rollback(),且对象是数据库连接对象,这里为cx。

3.3、select(选择)数据:

>>>cu.execute("select * from catalog;")

>>>cu.fetchall()

[(0,0, 'name2'), (1, 0, 'hello')]

fetchall()返回结果集中的全部数据,结果为一个tuple的列表。每个tuple元素是按建表的字段顺序排列。注意,游标是有状态的,它可以记录当前已经取到结果的第几个记录了,因此,一般你只可以遍历结果集一次。在上面的情况下,如果执行fetchone()会返回为空。这一点在测试时需要注意。

>>>cu.execute("select * from catalog where id = 1")

>>>cu.fetchone()

(1,0, 'hello')

对数据库没有修改的语句,执行后不需要再执行事务语句。

3.4、update(修改)数据:

>>>cu.execute("update catalog set name='name2' where id =?",(1,))

>>>cx.commit()

>>>cu.execute("select * from catalog")

>>>cu.fetchone()

(0,0, 'name2')

3.5、delete(删除)数据:

>>>cu.execute("delete from catalog where id = ?",(1,))

>>>cx.commit()

>>>cu.execute("select * from catalog")

>>>cu.fetchall()

[(0,0, 'name2')]

相关内容