Welcome 微信登录

首页 / 数据库 / MySQL / 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")]编写简单的连接MongoDB数据库C++程序 && 解决编译C++程序时链接MongoDB动态库失败的问题在Python 2.7平台下访问MySQL 5.0数据库相关资讯      python  sqlite 
  • Ubuntu 16.04 安装可视化数据库浏  (05月20日)
  • iOS 数据库比较:SQLite vs. Core   (03月01日)
  • 如何在 Ubuntu 15.04 上安装带   (02月09日)
  • 微软推荐通用 Windows 应用开发者  (05月04日)
  • SQLite 3.11.0 发布下载  (02月17日)
  • SQLite 3.10.2 发布下载  (01月29日)
本文评论 查看全部评论 (0)
表情: 姓名: 字数