openresty 学习笔记番外篇:python

折腾这个是因为想通过python从rabbitmq获取到消息后对mysql进行更新,所以这里就涉及两方面内容,一是python与mq的连接,二是python操作mysql

python操作mysql

MySQLdb 是用于Python链接Mysql数据库的接口,它实现了 Python 数据库 API 规范 V2.0,基于 MySQL C API 上建立的。

检查是否已经安装MySQLdb

为了用DB-API编写MySQL脚本,必须确保已经安装了MySQL。复制以下代码,并执行:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb

如果执行后的输出结果如下所示,意味着你没有安装 MySQLdb 模块

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    import MySQLdb
ImportError: No module named MySQLdb

安装MySQLdb
yum install MySQL-python

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb

try:
    # 打开数据库连接
    db = MySQLdb.connect(host='127.0.0.1',
                         user='root',
                         passwd='19850302cs',
                         db='openresty',
                         port=3306)
except Exception as e:
    print e
    sys.exit()

# 使用cursor()方法获取操作游标 
cursor = db.cursor()

# SQL 插入语句
sql = "SELECT type,enable_flag,count,access_record_flag,limit_count FROM access_code where code = 12345 and enable_flag = 1 and limit_count > count"

try:
   # 执行sql语句
   cursor.execute(sql)
   # # 提交到数据库执行
   # db.commit()
   # 使用 fetchone() 方法获取一条数据库。
   results = cursor.fetchall()
   for row in results:
       type = row[0]
       enable_flag = row[1]
       count = row[2]
       access_record_flag = row[3]
       limit_count = row[4]
       # 打印结果
       print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
             (type, enable_flag, count, access_record_flag, limit_count) 
except Exception as e:
   # # Rollback in case there is any error
   # db.rollback()
   print e
   sys.exit()
# 关闭数据库连接
db.close()

安装pip

pip类似Centos里面的yum,安装Python扩展模块非常方便

yum install epel-release
yum install python-pip
yum clean all

安装 pika和torndb

pika是python操作rabbitmq的扩展库,torndb是对MySQL-python的二次封装,所以安装torndb也依然需要MySQL-python才可以使用

pip install pika
pip install torndb

添加新评论