做下笔记,使用python链接数据库

源代码如下:

#!/usr/bin/env python
# -*- coding: utf8 -*-

import sys
import MySQLdb
import simplejson as json

reload(sys)
sys.setdefaultencoding('utf-8')

def getInfo ():
    try:
        conn = MySQLdb.connect(host='127.0.0.1', user='root', passwd='root', db='analysis', port=3306, charset='utf8')
        try:
            cur = conn.cursor()
            sql = r'select * from logs order by id desc limit 1'
            cur.execute(sql)
            logs = cur.fetchall()
        finally:
            cur.close()
            conn.close()
    except Exception, e:
        print '数据库错误:', e
        return

    for log in logs:
    data = json.loads(logs[2])
    print data['header']['device_id']

if __name__ == '__main__':
    getInfo()