Python查询Mysql, sqlite时返回字典结构的代码

MySQLdb

MySQLdb默认查询结果都是返回tuple,输出时候不是很方便,必须按照0,1这样读取,无意中在网上找到简单的修改方法,就是传递一个cursors.DictCursor就行。默认程序:


import MySQLdb 
db = MySQLdb.connect(host = ´localhost´, user = ´root´, passwd = ´123456´, db = ´test´) 
cursor = db.cursor() 
cursor.execute(´select * from table´) 
rs = cursor.fetchall() 
print rs 

返回类似如下
((1000L, 0L), (2000L, 0L), (3000L, 0L))
修改后:

import MySQLdb 
import MySQLdb.cursors 
db = MySQLdb.connect(host = ´localhost´, user = ´root´, passwd = ´123456´, db = ´test´,cursorclass = MySQLdb.cursors.DictCursor) 
cursor = db.cursor() 
cursor.execute(´select * from table´) 
rs = cursor.fetchall() 
print rs 

返回类似如下
({‘age’: 0L, ‘num’: 1000L}, {‘age’: 0L, ‘num’: 2000L}, {‘age’: 0L, ‘num’: 3000L}) 或者也可以用下面替换connect和cursor部分

db = MySQLdb.connect(host = ´localhost´, user = ´root´, passwd = ´123456´, db = ´test´) 
cursor = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor) 

参考:http://www.jb51.net/article/30597.htm

或者也可以用下面替换connect和cursor部分
db = MySQLdb.connect(host = ‘localhost’, user = ‘root’, passwd = ´123456´, db = ´test´)
cursor = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)

SQLite

1 查询记录条数
新建一个名为query-cpu-temp.py的文件,文件内容如下。

# -*- coding: utf-8 -*-  
import sqlite3  

# 连接数据库  
con = sqlite3.connect("cpu.db")  
cur = con.cursor()  

name = 'RPi.CPU'  
# 查询记录总数  
cur.execute("select count(*) from temps where name=(?);", (name, ))  
total = cur.fetchone()  

# 返回元组类型  
print type(total)  
print type(total[0])   
print total[0]  
【简要说明】
【1】cur.execute("select count(*) from temps where name=(?);", (name, )) 查询表中字段name为RPi.CPU的记录总数
【2】cur.fetchone() 获得一条记录,返回的结果为元组类型。
【3】total[0],返回的结果为只有一个元素的元组类型,total[0]为记录总数,类型为Int。
【4】返回结果

# -*- coding: utf-8 -*-  
import sqlite3  

# 连接数据库  
con = sqlite3.connect("cpu.db")  
cur = con.cursor()  

name = 'RPi.CPU'  
# 查询数据库,获得最近一小时的记录  
cur.execute('''''SELECT * FROM temps 
                WHERE name=(?) AND tdatetime > datetime('now', 'localtime', '-1 hours') 
                ORDER BY tdatetime ASC;''', (name, ))  
# 获得所有结果                  
rows = cur.fetchall()  

for row in rows:  
    print row  
【简要说明】
【1】WHERE name=(?) AND tdatetime > datetime('now', 'localtime', '-1 hours') ,查询一小时之前的温度参数, 'localtime'表示本时区时间。
【2】cur.fetchall() 获得符合条件的所有记录。
【3】返回的结果为列表类型,而类表中的每个元素为元组类型

(u’RPi.CPU’, u’2014-08-04 20:07:53’, 46.5)
(u’RPi.CPU’, u’2014-08-04 20:12:53’, 46.5)
(u’RPi.CPU’, u’2014-08-04 20:17:53’, 46.5)
(u’RPi.CPU’, u’2014-08-04 20:22:54’, 47.1)
(u’RPi.CPU’, u’2014-08-04 20:27:54’, 47.1)
(u’RPi.CPU’, u’2014-08-04 20:32:54’, 47.6)
(u’RPi.CPU’, u’2014-08-04 20:37:54’, 46.5)
(u’RPi.CPU’, u’2014-08-04 20:42:54’, 47.6)
(u’RPi.CPU’, u’2014-08-04 20:47:54’, 47.1)
(u’RPi.CPU’, u’2014-08-04 20:52:54’, 47.1)
(u’RPi.CPU’, u’2014-08-04 20:57:54’, 47.6)
(u’RPi.CPU’, u’2014-08-04 21:02:55’, 47.6)

3 转化为字典格式的工厂方法
在进行网络传输的过程中,多数通过JSON数据格式进行交换,在python中字典格式能更好的转换为JSON格式。

# -*- coding: utf-8 -*-  
import sqlite3  

def dict_factory(cursor, row):  
    d = {}  
    for idx, col in enumerate(cursor.description):  
        d[col[0]] = row[idx]  
    return d  

# 连接数据库  
con = sqlite3.connect("cpu.db")  
# 指定工厂方法  
con.row_factory = dict_factory  
cur = con.cursor()  

name = 'RPi.CPU'  
# 查询数据库,获得最近一小时的记录  
cur.execute('''''SELECT * FROM temps 
                WHERE name=(?) AND tdatetime > datetime('now', 'localtime', '-1 hours') 
                ORDER BY tdatetime ASC;''', (name, ))  

rows = cur.fetchall()  

for row in rows:  
    print row  
【简单说明】
【1】def dict_factory(cursor, row): 元组类型转换为字典类型,该函数来自python sqlite说明文档。
【2】con.row_factory = dict_factory 指定工厂方法
【3】返回结果,请注意()变为了{},表明返回结果为字典类型。

{‘tdatetime’: u’2014-08-04 20:22:54’, ‘name’: u’RPi.CPU’, ‘temperature’: 47.1}
{‘tdatetime’: u’2014-08-04 20:27:54’, ‘name’: u’RPi.CPU’, ‘temperature’: 47.1}
{‘tdatetime’: u’2014-08-04 20:32:54’, ‘name’: u’RPi.CPU’, ‘temperature’: 47.6}
{‘tdatetime’: u’2014-08-04 20:37:54’, ‘name’: u’RPi.CPU’, ‘temperature’: 46.5}
{‘tdatetime’: u’2014-08-04 20:42:54’, ‘name’: u’RPi.CPU’, ‘temperature’: 47.6}
{‘tdatetime’: u’2014-08-04 20:47:54’, ‘name’: u’RPi.CPU’, ‘temperature’: 47.1}
{‘tdatetime’: u’2014-08-04 20:52:54’, ‘name’: u’RPi.CPU’, ‘temperature’: 47.1}
{‘tdatetime’: u’2014-08-04 20:57:54’, ‘name’: u’RPi.CPU’, ‘temperature’: 47.6}
{‘tdatetime’: u’2014-08-04 21:02:55’, ‘name’: u’RPi.CPU’, ‘temperature’: 47.6}
{‘tdatetime’: u’2014-08-04 21:07:55’, ‘name’: u’RPi.CPU’, ‘temperature’: 47.1}
{‘tdatetime’: u’2014-08-04 21:12:55’, ‘name’: u’RPi.CPU’, ‘temperature’: 47.1}
{‘tdatetime’: u’2014-08-04 21:17:55’, ‘name’: u’RPi.CPU’, ‘temperature’: 47.6}

4 总结
【1】获得数据库记录的方法有 fetchone和fetchall。
【2】默认情况下返回元组结果。
【3】需要通过修改row_factory属性,把元组类型转换为字典类型。

参考:http://blog.csdn.net/xukai871105/article/details/38375729

5 row_factory
参考:https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.row_factory

row_factory
You can change this attribute to a callable that accepts the cursor and the original row as a tuple and will return the real result row. This way, you can implement more advanced ways of returning results, such as returning an object that can also access columns by name.

Example:

import sqlite3

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

con = sqlite3.connect(":memory:")
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print cur.fetchone()["a"]

If returning a tuple doesn’t suffice and you want name-based access to columns, you should consider setting row_factory to the highly-optimized sqlite3.Row type. 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.

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 对于Python问答系统,我们需要先确定输入的问题和回答的数据源,可以使用已有的问答对或者从网站、文档等资料中爬取数据。一些常用的Python库可以帮助我们实现这一过程,比如Beautiful Soup和urllib库。 接下来,我们需要将数据源中的问答对存储到适当的数据结构中,比如字典、列表或数据库中。在用户输入问题后,我们需要将输入文本进行预处理,去除停用词等无用信息,并将关键词提取出来。一些常用的Python自然语言处理库可以用来实现这个过程,如nltk库、spaCy库等。 然后,我们可以使用算法(如余弦相似度)进行问答匹配,并从数据源中找到最接近的问答对,将其返回给用户作为回答。在编写代码需要注意效率和准确性,尽量避免垃圾回答或重复回答的情况发生。 最后,我们可以将问答系统部署到网络上,或者与其他系统进行集成。如果需要改善系统的性能,我们可以使用一些技术,如缓存、并发处理、负载均衡等。 ### 回答2: Python问答系统是一个基于自然语言处理技术实现的人机交互系统,其通过处理自然语言输入,结合预设规则,返回相应的回答。下面是一个简单的Python问答系统代码示例: import re #导入正则表达式模块 import random #导入随机模块 #定义回答列表 answers = { "你好": ["你好啊", "很高兴见到你", "你好呀"], "再见": ["下次再见", "再见了", "拜拜"], "天气": ["今天天气晴朗", "今天有点阴", "今天下雨了"], "笑话": ["小明考试不及格,老师问他怎么回事,小明说:我脑子里只有你教的题目。", "为什么女生胖了会被男生嫌弃? 因为上压力大了,下按不鸟了!"] } #定义问题和回答函数 def ask_question(text): for question, answer in answers.items(): match = re.search(question, text) if match: return random.choice(answer) #主程序 while True: user_input = input("> ") if user_input == "退出": break response = ask_question(user_input) if response: print(response) else: print("我不明白你的问题") 上述代码中,我们首先定义了一个回答列表(answers),其中包含了用户可能输入的问题和对应的回答。接下来我们定义了一个问答函数(ask_question),当用户输入问题,我们通过正则表达式处理用户输入,从而判断用户的问题是否和回答列表中的某个问题相匹配。若匹配成功,则返回该问题对应的回答;若匹配失败,则返回默认的“我不明白你的问题”回答。 在主程序中,我们通过循环接收用户的输入,并将其传递给问答函数。如果问答函数成功匹配了问题,就将对应的回答输出到屏幕上。如果匹配失败,则输出默认的回答。在用户输入“退出”,程序将会终止循环并退出。 ### 回答3: 对于一个Python问答系统的代码来说,首先需要明确系统的需求与功能。该系统需要能够接收用户输入的问题,从数据库中查询到相应的问题答案,并将答案返回给用户。 在代码实现中,可以通过使用Python的Flask框架搭建Web应用,通过前端页面实现和用户的交互。使用Flask可以简便地实现请求和响应的处理,通过路由机制实现对不同URL的请求的响应。同需要连接到后端的数据库,可以选择SQLite或者MySQL等数据库,用以存储问题和答案的数据信息。 在解决用户的问题的候,可以通过预先定义好的问题分类,实现对输入问题的分类判定。同还可以通过一些机器学习算法提取问题的特征,进一步提高准确率。对于问题的答案,可以通过数据库中存储的信息进行检索,同还可以通过在网络上搜索相关的资源来获得更全面的答案。 代码实现的过程中,需要注意系统的实性和可扩展性。系统需要支持并发和大量数据的存储和查询。开发者还应当充分考虑到系统的效率和安全性。同,开放API接口也可以使得系统更加易于扩展和与其他系统集成。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值