1.导入Python SQLITE数据库模块

Python2.5之后,内置了SQLite3,成为了内置模块,这给我们省了安装的功夫,只需导入即可~

  1. import sqlite3
  2.  
  3. 2. 创建/打开数据库
  4.      在调用connect函数的时候,指定库名称,如果指定的数据库存在就直接打开这个数据库,如果不存在就新创建一个再打开。
  5.  
  6. cx = sqlite3.connect("E:/test.db")
  7.  
  8.      也可以创建数据库在内存中。
  9.  
  10. con = sqlite3.connect(":memory:")
  11.  
  12. 3.数据库连接对象
  13.     打开数据库时返回的对象cx就是一个数据库连接对象,它可以有以下操作:
  14.  
  15. commit()--事务提交   
  16. rollback()--事务回滚   
  17. close()--关闭一个数据库连接   
  18. cursor()--创建一个游标
  19.  
  20.     关于commit(),如果isolation_level隔离级别默认,那么每次对数据库的操作,都需要使用该命令,你也可以设置isolation_level=None,这样就变为自动提交模式。
  21. 4.使用游标查询数据库
  22.     我们需要使用游标对象SQL语句查询数据库,获得查询对象。 通过以下方法来定义一个游标。
  23.  
  24. cu=cx.cursor()
  25.  
  26.  
  27.      游标对象有以下的操作:
  28. execute()--执行sql语句   
  29. executemany--执行多条sql语句   
  30. close()--关闭游标   
  31. fetchone()--从结果中取一条记录,并将游标指向下一条记录   
  32. fetchmany()--从结果中取多条记录   
  33. fetchall()--从结果中取出所有记录   
  34. scroll()--游标滚动  
  35.  
  36. 1. 建表
  37.  
  38. cu.execute("create table catalog (id integer primary key,pid integer,name varchar(10) UNIQUE,nickname text NULL)")
  39.  
  40.  
  41. 上面语句创建了一个叫catalog的表,它有一个主键id,一个pid,和一个namename是不可以重复的,以及一个nickname默认为NULL
  42.  
  43. 2. 插入数据
  44. 请注意避免以下写法:
  45.  
  46. # Never do this -- insecure 会导致注入攻击
  47.  
  48. pid=200
  49. c.execute("... where pid = '%s'" % pid)
  50.  
  51. 正确的做法如下,如果t只是单个数值,也要采用t=(n,)的形式,因为元组是不可变的。
  52.  
  53. for t in[(0,10,'abc','Yu'),(1,20,'cba','Xu')]:
  54.     cx.execute("insert into catalog values (?,?,?,?)", t)
  55.  
  56. 简单的插入两行数据,不过需要提醒的是,只有提交了之后,才能生效.我们使用数据库连接对象cx来进行提交commit和回滚rollback操作.
  57.  
  58. cx.commit()
  59.  
  60.  
  61.  
  62. 3.查询
  63.  
  64. cu.execute("select * from catalog")
  65.  
  66. 要提取查询到的数据,使用游标的fetch函数,如:
  67.  
  68. In [10]: cu.fetchall()
  69. Out[10]: [(0, 10, u'abc', u'Yu'), (1, 20, u'cba', u'Xu')]
  70.  
  71. 如果我们使用cu.fetchone(),则首先返回列表中的第一项,再次使用,则返回第二项,依次下去.
  72.  
  73. 4.修改
  74.  
  75. In [12]: cu.execute("update catalog set name='Boy' where id = 0")
  76. In [13]: cx.commit()
  77.  
  78. 注意,修改数据以后提交
  79.  
  80. 5.删除
  81.  
  82. cu.execute("delete from catalog where id = 1")  
  83. cx.commit()
  84.  
  85.  
  86. 6.使用中文
  87. 请先确定你的IDE或者系统默认编码是utf-8,并且在中文前加上u
  88.  
  89. x=u'鱼'
  90. cu.execute("update catalog set name=? where id = 0",x)
  91. cu.execute("select * from catalog")
  92. cu.fetchall()
  93. [(0, 10, u'\u9c7c', u'Yu'), (1, 20, u'cba', u'Xu')]
  94.  
  95. 如果要显示出中文字体,那需要依次打印出每个字符串
  96.  
  97. In [26]: for item in cu.fetchall():
  98.    ....:     for element in item:
  99.    ....:         print element,
  100.    ....:     print
  101.    ....: 
  102. 0 10  Yu
  103. 1 20 cba Xu
  104.  
  105.  
  106. 7.Row类型
  107.  
  108. Row提供了基于索引和基于名字大小写敏感的方式来访问列而几乎没有内存开销。 原文如下:
  109.  
  110.  
  111. sqlite3.Row provides both index-based and
  112. case-insensitive name-based access to columns with almost no memory overhead. It
  113. will probably be better than your own custom dictionary-based approach or even a
  114. db_row based solution.
  115.  
  116.  
  117. Row对象的详细介绍
  118. class
  119. sqlite3.Row
  120. A Row instance serves as a highly optimized
  121. row_factory for Connection objects. It tries to mimic a tuple in most
  122. of its features.
  123. It supports mapping access by column
  124. name and index, iteration, representation, equality testing and len().
  125. If two Row objects have exactly the same columns and
  126. their members are equal, they compare equal.
  127. Changed in version 2.6: Added
  128. iteration and equality (hashability).
  129. keys()
  130. This method returns a tuple of
  131. column names. Immediately after a query, it is the first member of each tuple in
  132. Cursor.description.
  133. New in version
  134. 2.6.
  135.  
  136.     下面举例说明
  137.  
  138. In [30]: cx.row_factory = sqlite3.Row
  139.  
  140. In [31]: c = cx.cursor()
  141.  
  142. In [32]: c.execute('select * from catalog')
  143. Out[32]: <sqlite3.Cursor object at 0x05666680>
  144.  
  145. In [33]: r = c.fetchone()
  146.  
  147. In [34]: type(r)
  148. Out[34]: <type 'sqlite3.Row'>
  149.  
  150. In [35]: r
  151. Out[35]: <sqlite3.Row object at 0x05348980>
  152.  
  153. In [36]: print r
  154. (0, 10, u'\u9c7c', u'Yu')
  155.  
  156. In [37]: len(r)
  157. Out[37]: 4
  158.  
  159. In [39]: r[2]           
  160. #使用索引查询
  161. Out[39]: u'\u9c7c'
  162.  
  163. In [41]: r.keys()
  164. Out[41]: ['id', 'pid', 'name', 'nickname']
  165.  
  166. In [42]: for e in r:
  167.    ....:     print e,
  168.    ....: 
  169. 0 10  Yu
  170.  
  171.  使用列的关键词查询
  172.  
  173. In [43]: r['id']
  174. Out[43]: 0
  175.  
  176. In [44]: r['name']
  177. Out[44]: u'\u9c7c'

python操作轻量级数据库的更多相关文章

  1. python操作mysql数据库的相关操作实例

    python操作mysql数据库的相关操作实例 # -*- coding: utf-8 -*- #python operate mysql database import MySQLdb #数据库名称 ...

  2. Python操作Access数据库

    我们在这篇文章中公分了五个步骤详细分析了Python操作Access数据库的相关方法,希望可以给又需要的朋友们带来一些帮助. AD: Python编 程语言的出现,带给开发人员非常大的好处.我们可以利 ...

  3. Windows下安装MySQLdb, Python操作MySQL数据库的增删改查

    这里的前提是windows上已经安装了MySQL数据库,且配置完成,能正常建表能操作. 在此基础上仅仅需安装MySQL-python-1.2.4b4.win32-py2.7.exe就ok了.仅仅有1M ...

  4. 使用python操作mysql数据库

    这是我之前使用mysql时用到的一些库及开发的工具,这里记录下,也方便我查阅. python版本: 2.7.13 mysql版本: 5.5.36 几个python库 1.mysql-connector ...

  5. python操作三大主流数据库(10)python操作mongodb数据库④mongodb新闻项目实战

    python操作mongodb数据库④mongodb新闻项目实战 参考文档:http://flask-mongoengine.readthedocs.io/en/latest/ 目录: [root@n ...

  6. python操作三大主流数据库(9)python操作mongodb数据库③mongodb odm模型mongoengine的使用

    python操作mongodb数据库③mongodb odm模型mongoengine的使用 文档:http://mongoengine-odm.readthedocs.io/guide/ 安装pip ...

  7. python操作三大主流数据库(8)python操作mongodb数据库②python使用pymongo操作mongodb的增删改查

    python操作mongodb数据库②python使用pymongo操作mongodb的增删改查 文档http://api.mongodb.com/python/current/api/index.h ...

  8. python操作三大主流数据库(7)python操作mongodb数据库①mongodb的安装和简单使用

    python操作mongodb数据库①mongodb的安装和简单使用 参考文档:中文版:http://www.mongoing.com/docs/crud.html英文版:https://docs.m ...

  9. python操作三大主流数据库(1)python操作mysql①windows环境中安装python操作mysql数据库的MySQLdb模块mysql-client

    windows安装python操作mysql数据库的MySQLdb模块mysql-client 正常情况下应该是cmd下直接运行 pip install mysql-client 命令即可,试了很多台 ...

随机推荐

  1. 关于HTML5视频标签的问题

    一.基本 video标签在兼容性上还是比较差的,如果要在页面中使用video标签,需要考虑三种情况,支持Ogg Theora或者VP8的(Opera.Mozilla.Chrome),支持H.264的( ...

  2. Machine Learning(Andrew Ng)学习笔记

    1.监督学习(supervised learning)&非监督学习(unsupervised learning) 监督学习:处理具有若干属性且返回值不同的对象.分为回归型和分类型:回归型的返回 ...

  3. JDK8日期处理API(转)

    转载地址:http://www.cnblogs.com/comeboo/p/5378922.html 转载地址:http://blog.csdn.net/hspingcc/article/detail ...

  4. VIDENT iSmart900自动多系统扫描工具OBDII支持ABS / SRS / EPB /传输诊断DPF再生/上油复位编码电池配置

    Vident系列中有许多多功能产品,其中最好的是Vident iSmart 900.购买视频系列后,以下是用户的一些评论 乔:因为我想它很好用.该工具很容易更新.我将公制重量单位的代码放到工具中.很容 ...

  5. vue 手机物理返回键关闭弹框

    1.打开弹窗调用 window.history.pishState() 函数 2.关闭弹框 3.mounted 生命周期 监听popstate 事件 4.beforeDestroy 生命周期 移除po ...

  6. windows查看服务的状态

    方法一:运行窗口操作 按下win+r键,在运行窗口中输入services.msc,点击[确定]按钮,即可打开服务. 如下图所示: 方法二:按部就班 1)此电脑—右键—管理 2)点击[服务和应用程序]按 ...

  7. js的DOM操作整理(整理)

    js的DOM操作整理(整理) 一.总结 一句话总结: dom操作有用原生js的dom操作,也可以用对js封装过的jquery等插件来更加方便的进行dom操作 1.dom是什么? 对于JavaScrip ...

  8. Spring Batch 4.2 新特性

    Spring Batch 4.2 的发行版主要增强了下面的改进: 使用 Micrometer 来支持批量指标(batch metrics) 支持从 Apache Kafka topics 读取/写入( ...

  9. JavaWeb-SpringSecurity实现需求-判断请求是否以html结尾

    系列博文 项目已上传至guthub 传送门 JavaWeb-SpringSecurity初认识 传送门 JavaWeb-SpringSecurity在数据库中查询登陆用户 传送门 JavaWeb-Sp ...

  10. HDU 5793 A Boring Question ——(找规律,快速幂 + 求逆元)

    参考博客:http://www.cnblogs.com/Sunshine-tcf/p/5737627.html. 说实话,官方博客的推导公式看不懂...只能按照别人一样打表找规律了...但是打表以后其 ...