Heim  >  Artikel  >  Backend-Entwicklung  >  Python实现Sqlite将字段当做索引进行查询的方法

Python实现Sqlite将字段当做索引进行查询的方法

WBOY
WBOYOriginal
2016-08-04 08:55:391904Durchsuche

本文实例讲述了Python实现Sqlite将字段当做索引进行查询的方法。分享给大家供大家参考,具体如下:

默认从sqlite中获取到的数据是数字索引的, 在开发阶段经常有修改数据库所以显得不太方便, 其实在python源码里就有解决方案, 直接读sqlite3的源码, 摸索了一些, 解决方案如下:

默认连接的话使用一下代码是以数字为索引的:

conn = sqlite3.connect(dbfile)
cur = conn.cursor()

为了使得获取到的结果集以字段为索引, 需要添加一个函数和一个类:

def dict_factory(cursor, row):
  d = {}
  for idx, col in enumerate(cursor.description):
    d[col[0]] = row[idx]
  return d
class MyCursor(sqlite3.Cursor):
  def __init__(self, *args, **kwargs):
    sqlite3.Cursor.__init__(self, *args, **kwargs)
    self.row_factory = dict_factory

然后修改连接的代码:

conn = sqlite3.connect(dbfile)
cur = conn.cursor(factory=MyCursor)

之后读取出来的便是以字段为索引的了.

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

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

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn