Python操作SQLite数据库的方法详解


当前第2页 返回上一页

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相关内容感兴趣的读者可查看本站专题:《Python常见数据库操作技巧汇总》、《Python编码操作技巧总结》、《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。


标签:SQLite

返回前面的内容

相关阅读 >>

springboot项目中内嵌Sqlite数据库的配置流程

android开发实现的导出数据库到excel表格功能【附源码下载】

c#操作Sqlite方法实例详解

Sqlite教程(十二):锁和并发控制详解

Sqlite教程(三):数据表和视图简介

android 架构之数据库框架搭建

Sqlite 入门教程四&nbsp;&nbsp;增删改查 有讲究

详解android数据存储之sqlcipher数据库加密

Sqlitestudio打开后如何切换成简体中文Sqlitestudio绿色版中文设置方法介绍

ios app中数据管理框架core data的基本数据操作教程

更多相关阅读请进入《Sqlite》频道 >>


数据库系统概念 第6版
书籍

数据库系统概念 第6版

机械工业出版社

本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...