1.导入Python SQLITE数据库模块

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

import sqlite3

2. 创建/打开数据库
     在调用connect函数的时候,指定库名称,如果指定的数据库存在就直接打开这个数据库,如果不存在就新创建一个再打开。 cx = sqlite3.connect("E:/test.db")      也可以创建数据库在内存中。 con = sqlite3.connect(":memory:") 3.数据库连接对象
    打开数据库时返回的对象cx就是一个数据库连接对象,它可以有以下操作: commit()--事务提交   
rollback()--事务回滚   
close()--关闭一个数据库连接   
cursor()--创建一个游标     关于commit(),如果isolation_level隔离级别默认,那么每次对数据库的操作,都需要使用该命令,你也可以设置isolation_level=None,这样就变为自动提交模式。
4.使用游标查询数据库
    我们需要使用游标对象SQL语句查询数据库,获得查询对象。 通过以下方法来定义一个游标。 cu=cx.cursor()  
     游标对象有以下的操作:
execute()--执行sql语句   
executemany--执行多条sql语句   
close()--关闭游标   
fetchone()--从结果中取一条记录,并将游标指向下一条记录   
fetchmany()--从结果中取多条记录   
fetchall()--从结果中取出所有记录   
scroll()--游标滚动   1. 建表 cu.execute("create table catalog (id integer primary key,pid integer,name varchar(10) UNIQUE,nickname text NULL)")  
上面语句创建了一个叫catalog的表,它有一个主键id,一个pid,和一个name,name是不可以重复的,以及一个nickname默认为NULL。
 
2. 插入数据
请注意避免以下写法: # Never do this -- insecure 会导致注入攻击 pid=200
c.execute("... where pid = '%s'" % pid) 正确的做法如下,如果t只是单个数值,也要采用t=(n,)的形式,因为元组是不可变的。 for t in[(0,10,'abc','Yu'),(1,20,'cba','Xu')]:
    cx.execute("insert into catalog values (?,?,?,?)", t) 简单的插入两行数据,不过需要提醒的是,只有提交了之后,才能生效.我们使用数据库连接对象cx来进行提交commit和回滚rollback操作. cx.commit()  
 
3.查询 cu.execute("select * from catalog") 要提取查询到的数据,使用游标的fetch函数,如: In [10]: cu.fetchall()
Out[10]: [(0, 10, u'abc', u'Yu'), (1, 20, u'cba', u'Xu')] 如果我们使用cu.fetchone(),则首先返回列表中的第一项,再次使用,则返回第二项,依次下去.
 
4.修改 In [12]: cu.execute("update catalog set name='Boy' where id = 0")
In [13]: cx.commit() 注意,修改数据以后提交
 
5.删除 cu.execute("delete from catalog where id = 1")  
cx.commit()  
6.使用中文
请先确定你的IDE或者系统默认编码是utf-8,并且在中文前加上u x=u'鱼'
cu.execute("update catalog set name=? where id = 0",x)
cu.execute("select * from catalog")
cu.fetchall()
[(0, 10, u'\u9c7c', u'Yu'), (1, 20, u'cba', u'Xu')] 如果要显示出中文字体,那需要依次打印出每个字符串 In [26]: for item in cu.fetchall():
   ....:     for element in item:
   ....:         print element,
   ....:     print
   ....: 
0 10 鱼 Yu
1 20 cba Xu  
7.Row类型
 
Row提供了基于索引和基于名字大小写敏感的方式来访问列而几乎没有内存开销。 原文如下:
  sqlite3.Row provides both index-based and
case-insensitive name-based access to columns with almost no memory overhead. It
will probably be better than your own custom dictionary-based approach or even a
db_row based solution.  
Row对象的详细介绍
class
sqlite3.Row
A Row instance serves as a highly optimized
row_factory for Connection objects. It tries to mimic a tuple in most
of its features.
It supports mapping access by column
name and index, iteration, representation, equality testing and len().
If two Row objects have exactly the same columns and
their members are equal, they compare equal.
Changed in version 2.6: Added
iteration and equality (hashability).
keys()
This method returns a tuple of
column names. Immediately after a query, it is the first member of each tuple in
Cursor.description.
New in version
2.6.     下面举例说明 In [30]: cx.row_factory = sqlite3.Row In [31]: c = cx.cursor() In [32]: c.execute('select * from catalog')
Out[32]: <sqlite3.Cursor object at 0x05666680> In [33]: r = c.fetchone() In [34]: type(r)
Out[34]: <type 'sqlite3.Row'> In [35]: r
Out[35]: <sqlite3.Row object at 0x05348980> In [36]: print r
(0, 10, u'\u9c7c', u'Yu') In [37]: len(r)
Out[37]: 4 In [39]: r[2]           
#使用索引查询
Out[39]: u'\u9c7c' In [41]: r.keys()
Out[41]: ['id', 'pid', 'name', 'nickname'] In [42]: for e in r:
   ....:     print e,
   ....: 
0 10 鱼 Yu  使用列的关键词查询 In [43]: r['id']
Out[43]: 0 In [44]: r['name']
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. JAVA面试/笔试经典题

    1.short s1 = 1; s1 = s1 + 1;有什么错? short s1 = 1; s1 += 1;有什么错? 对于short s1 = 1; s1 = s1 + 1; 由于s1+1运算时 ...

  2. k8sSecret资源

    Secret资源的功能类似于ConfigMap,但它专用于存放敏感数据,如密码.数字证书.私钥.令牌和ssh key等. 一.概述 Secret对象存储数据以键值方式存储数据,再pod资源中通过环境变 ...

  3. 5天noip训练心得

    day1 100+95+0=195 T1 二分答案,并查集,很像noip2017 day2 T1 T2 缩环,然后数据结构维护求答案,貌似也是原题 T3 树形dp,比赛上没有做出来, day2 90+ ...

  4. Bootloader - Main system - Recovery的三角关系

    原文地址:http://blog.csdn.net/myarrow/article/details/8115610 一.MTD分区:BOOT:        boot.img,Linux kernel ...

  5. ZOJ - 4045District Division dfs划分子树

    ZOJ - 4045District Division 题目大意:给你n个节点的树,然后让你划分这棵数使得,每一块都恰好k个节点并且两两间是连通的,也就是划分成n/k个连通集,如果可以输出YES,并输 ...

  6. 洛谷p2375 kmp

    题意 给你一个字符串,让你求一个\(num\)数组,\(num[i]\)为长度为\(i\)的前缀的公共前后缀长度不超过\(\lfloor \frac{i}{2}\rfloor\)的个数, 例如&quo ...

  7. java中如何补齐汉字字符

    一个汉字相当于两个字符,所以需要输入法的时候切换到[中文全角],中文全角占用2个字符(一个空格),半角占用1个字符

  8. Jmeter(六)关联之XPath提取器

    如果请求返回的消息为xml或html格式的,可以用XPath提取器来提取需要的数据 以http://www.weather.com.cn/为例: 先新建一个HTTP请求GetCityURL,获取城市天 ...

  9. 「HNOI2014」世界树

    题目链接 问题分析 首先观察数据范围可以知道要用虚树.但是要考虑怎么维护原树的距离信息. 如果只有两个关键点,我们可以很方便地找到中点将整棵树划分为两部分.而如果有多个关键点,看起来有效的方法就是多源 ...

  10. Nginx一个server配置多个location

    在配置文件中增加多个location,每个location对应一个项目 比如使用8066端口,location / 访问官网: location /demo访问培训管理系统配置多个站点我选择了配置多个 ...