Application of python Config and pymysql

1. Read the configuration file
configuration file conf.ini in python
[MONGODB]
#mongodb database server IP address
host=10.43.110.93
#mongodb port
port=40001
#mongodb connection database name
database=data_collect
[MYSQL]
mysql_user=root
mysql_pwd=root
mysql_url=127.0.0.1
mysql_database=passport_sx

python code Config.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "jiandequn"
import ConfigParser
class config:
    def __init__(self,path):
        self.config = ConfigParser.ConfigParser()
        self.config.readfp(open(path))
    def getValue(self,section,key):
        return self.config.get(section, key)

if __name__ == "__main__":
    conf = config("conf.ini");
    host = conf.getValue("MONGODB", "host");
    port = conf.getValue("MONGODB", "port");
    database = conf.getValue("MONGODB", "database");
    print host
    print port
    print database



python operation mysql
# -*- coding: UTF-8 -*-


import pymysql

# Open database connection
from Config import config

"""mysql初始化"""
class mysql_init:
    def __init__(self):
        conf = config("conf.ini");
        url = conf.getValue("MYSQL", "mysql_url");
        username = conf.getValue("MYSQL", "mysql_user");
        password = conf.getValue("MYSQL", "mysql_pwd");
        database = conf.getValue("MYSQL", "mysql_database");
        self.db = pymysql.connect(url,username, password, database, charset='utf8')
    """Query data"""
    def query(self,select):
        cursor =  self.db.cursor();
        # Execute the SQL query using the execute() method
        cursor.execute(select)
        return cursor.fetchall()
    def close(self):
        self.db.close()
if __name__ == "__main__":
    t = mysql_init();
    # sql = """SELECT
    #              a.mac,
    #                 a.sn,
    #                 b.user_id
    #             FROM
    #                 tb_user a ,
    #              resume_point b
    #             where
    #               a.auth_code = b.user_id
    #               and b.create_time<='2017-05-31'
    #             group by a.mac,a.sn""";
    c = t.query("select mac,sn from user_view_temp");
    for row in c:
        print row
    t.close();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326177613&siteId=291194637