码迷,mamicode.com
首页 > 数据库 > 详细

Python连接Mysql、Influxdb、Redis的方法

时间:2018-09-12 22:08:36      阅读:415      评论:0      收藏:0      [点我收藏+]

标签:python   read   mysq   __name__   文件   safe   mysqld   load   1.4   

一、在配置文件中配置相关连接参数

在conf.ini中:
#mysql参数

[Mysql]
host = 192.168.1.2
port = 3306
user = root
passwd = pswdmysql
db = student

#InfluxDB参数
[InfluxDB]
host = 192.168.1.3
port = 8086
user = root
passwd = pswdinflux
db = student

#Redis参数
[InfluxDB]
host = 192.168.1.4
port = 6379
user = root
passwd = pswdredis

二、读取配置文件参数,返回连接对象``


/usr/bin/env python
coding:utf-8
auther:yuanmuc
connect to mysql,influxdb,redis
from influxdb import InfluxDBClient
import MySQLdb
import redis
import sys
reload(sys)
sys.setdefaultencoding(‘uft-*8‘)
def DBcon():
            cf = ConfigParser.SafeConfigParser()
            cf.read("conf.ini")
            mysql的参数
            MysqlHost = cf.get(‘Mysql‘,‘host‘)
            MysqlPort = cf.get(‘Mysql‘,‘port‘)
            MysqlUser = cf.get(‘Mysql‘, ‘user‘)
            MysqlPwd = cf.get(‘Mysql‘, ‘passwd‘)
            MysqlDb = cf.get(‘Mysql‘, ‘db‘)
            influxdb的参数
            InfHost = cf.get(‘InfluxDB‘,‘host‘)
            InfPort = cf.get(‘InfluxDB‘, ‘port‘)
            InfUser = cf.get(‘InfluxDB‘, ‘user‘)
            InfPwd = cf.get(‘InfluxDB‘, ‘passwd‘)
            InfDB = cf.get(‘InfluxDB‘, ‘db‘)
            redis的参数
            RedisHost = cf.get(‘Redis‘,‘host‘)
            RedisPort = cf.get(‘Redis‘, ‘port‘)
            RedisUser = cf.get(‘Redis‘, ‘user‘)
            RedisPwd = cf.get(‘Redis‘, ‘passwd‘)
            #连接mysql
            MysqlCon = MySQLdb.connect(host=MysqlHost,port=int(MysqlPort),user=MysqlUser,passwd=MysqlPwd,db=MysqlDb,charset=‘utf-8‘)
            MysqlCur = MysqlCon.cursor()
            #连接influxdb
            Influxdb_Client = InfluxDBClient(InfHost,InfPort,InfUser,InfPwd,InfDB)
            #连接redis
            pool = redis.ConnectionPool(host=RedisHost,port=RedisPort,password=RedisPwd,decode_responses=True)
            Redis_Client = redis.Redis(connection_pool=pool)
            返回连接
            return MysqlCon,MysqlCur,Influxdb_Client,Redis_Client
def MysqlClose():
      MysqlCon.close()
      MysqlCur.close()

if __name__ == ‘__main__‘:
MysqlCon, MysqlCur, Influxdb_Client, Redis_Client = DBcon()

Python连接Mysql、Influxdb、Redis的方法

标签:python   read   mysq   __name__   文件   safe   mysqld   load   1.4   

原文地址:http://blog.51cto.com/12824426/2174471

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!