Python查询Mysql, sqlite时返回字典结构的代码
2017-08-21 12:01
796 查看
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 rs1
2
3
4
5
6
7
1
2
3
4
5
6
7
返回类似如下
((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 rs1
2
3
4
5
6
7
1
2
3
4
5
6
7
返回类似如下
({‘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)1
2
1
2
参考: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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
【简要说明】 【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 row1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
【简要说明】 【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 row1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
【简单说明】 【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属性,把元组类型转换为字典类型。
示例:在python2.7中:
def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d class MenuConfig: '类的局部变量' sql_cursor = sqlite3.Cursor sql_connect = sqlite3.Connection def __init__(self, sqlname, table): self.sqlname = sqlname self.table = table def OpenMenuConfigQDB(self): print "OpenMenuConfigQDB" # 连接数据库 MenuConfig.sql_connect = sqlite3.connect(self.sqlname) # 指定工厂方法 MenuConfig.sql_connect.row_factory = dict_factory # 获取焦点 MenuConfig.sql_cursor = MenuConfig.sql_connect.cursor() def GetAllParamOfNumberId(self, id): #根据ID值返回元祖-所有行的内容 print "GetAllParamOfNumberId" try: execute_str = 'select * from %s WHERE ID = %d;' % (self.table,id) cursor = MenuConfig.sql_cursor.execute(execute_str) except Exception, e: print str(e) MenuConfig.sql_connect.rollback() else: print 'success' rows = MenuConfig.sql_cursor.fetchall() MenuConfig.sql_connect.close() return rows def GetAllParamOfDefault(self):#返回元祖-默认所有行的内容 print "GetAllParamOfDefault" try: execute_str = 'select * from %s WHERE ID = 1;' % self.table MenuConfig.sql_cursor.execute(execute_str) except Exception, e: print str(e) MenuConfig.sql_connect.rollback() else: print 'success' rows = MenuConfig.sql_cursor.fetchall() MenuConfig.sql_connect.close() return rows
menuconfigdb = MenuConfig('/opt/QDB/Battery.db','BATTERY_DB') menuconfigdb.OpenMenuConfigQDB() aastrs = menuconfigdb.GetAllParamOfDefault() print aastrs[0] print aastrs[0]['UpdataInterval'];
返回结果:
{'UpdataInterval': 60, 'Monitor': 0, 'DataModify': u'2011-10-16', 'MonitorLimits': 0, 'Delay': 0, 'Source': 0, 'AddChannels': 0, 'StartingRow': 0, 'StatusAndCmds': 0, 'LogFile': 0, 'TaskName': u'DMM Scan', 'Description': u'battery', 'Format': 0, 'UpdataIntervalUnit':
0, 'Timestamp': 0, 'Company': u'PSU', 'AddUnits': 0, 'DelayUnit': 0, 'ScrollDisplay': 0, 'TimerUnit': 0, 'CreateBy': u'labusers', 'Limits': 0, 'AutoWrap': 0, 'Timer': 0, 'StartingCol': 0, 'ReadingCount': 0, 'Model': 0, 'ID': 1, 'AddChannelTags': 0, 'DataCreated':
u'2017-07-05', 'WorkSheet': 0, 'OrganiseBy': 0, 'Antoncremen': 0}
60
相关文章推荐
- Python查询Mysql, sqlite时返回字典结构的代码
- Python查询Mysql, sqlite时返回字典结构的代码
- Python查询Mysql时返回字典结构的代码
- Python查询Mysql时返回字典结构的代码
- Python查询Mysql时返回字典结构的代码
- Python查询Mysql时返回字典结构的代码
- python mysql 查询返回字典结构
- Python中让MySQL查询结果返回字典类型的方法
- python mysqldb 查询返回字典结构
- Python Sqlite3以字典形式返回查询结果的实现方法
- Python中让MySQL查询结果返回字典类型的方法
- Python Sqlite3以字典形式返回查询结果的实现方法
- Python中让MySQL查询结果返回字典类型的方法
- python mysqldb 查询返回字典结构
- python连接mysql查询数据返回字典格式
- python3 MySQL 查询返回字典类型
- Python MySQLdb 查询返回字典结构
- Python中让MySQL查询结果返回字典类型的方法
- python mysqldb 查询返回字典结构
- python将字典内容存入mysql实例代码