配置文件conf.ini
[MONGODB] #mongodb数据库服务器IP地址 host=10.43.110.93 #mongodb端口 port=40001 #mongodb连接数据库名称 database=data_collect [MYSQL] mysql_user=root mysql_pwd=root mysql_url=127.0.0.1 mysql_database=passport_sx
python代码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操作mysql
# -*- coding: UTF-8 -*- import pymysql # 打开数据库连接 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') """查询数据""" def query(self,select): cursor = self.db.cursor(); # 使用 execute() 方法执行 SQL 查询 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();