1.  首页
  2.  博客
  3. Python链接MySQL数据库

Python链接MySQL数据库


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

源代码如下:

 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
26
27
28
29
30
31
#!/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()

评论 0