python 访问sqlite,使用装饰器封装,去掉重复的连接代码


 1 # -*- coding:utf-8 -*-
 2 
 3 import os
 4 import sqlite3
 5 import sys
 6 reload(sys)
 7 sys.setdefaultencoding('utf8')
 8 
 9 def get_con(func):
10     data_path = r'../db.sqlite3'
11     def sql_exc():
12         con = sqlite3.connect(unicode(data_path))
13         con.text_factory=str
14         cur = con.cursor()
15         func(cur)
16         cur.close()
17         con.close()
18     return sql_exc
19 
20 @get_con
21 def get_art(cur):
22     cur.execute('select * from blog_article ')
23     rows = cur.fetchall()
24     print rows
25 
26 @get_con
27 def get_nav(cur):
28     cur.execute('select * from blog_nav ')
29     rows = cur.fetchall()
30     for row in rows:
31         for i in row:
32             print str(i).encode('gbk')
33 
34 get_art()
35 
36 get_nav()

 


posted @ 2017-03-20 23:48  aloneOnWorld  阅读(1185)  评论(0编辑  收藏  举报