需要了解的知识
首先呢,你需要了解下DBUtils,我的描述肯定没官网解释来的清晰,自行阅读后,你就会发现我为什么会选用PooledDB而不是其他作为连接池了。
其次,DBUtils支持所有遵循DP-API 2规范的数据库连接模块,也就是说除了我示例中所提供的几个数据库连接方式外,各位可以探索其他遵循此标准的连接模块,从而在此基础上拓展,成为连接更多种类数据库的通用工具类。
最后,以下内容均基于python3。
---------------------------------------------------------
10.23增补内容:支持hbase,更新字典返回方式以及部分方法扩展。
准备工作
首先,pip下支持DB-API 2规范的相关数据库连接模块和DBUtils。
pip install DBUtils
pip install pymysql(mysql)
pip install pymssql(sqlserver)
pip install cx_Oracle(oracle)
pip install phoenixdb(hbase)
pip install sqlite3(sqlite3 python自带)
其次,需要准备一份配置文件,姑且命名为pdbc.properties,以下是示例,根据数据库的连接信息进行修改即可。
# 数据库类型,支持mysql,oracle,sqlserver,sqlite3,hbase
# --------------------------------------------------------------
# mysql
# 连接数据库host
host_mysql=ip
# 连接数据库port
port_mysql=3306
# 连接数据库库名
database_mysql=dbname
# 用户
user_mysql=username
# 密码
password_mysql=password
# 字符集
charset_mysql=utf8
# --------------------------------------------------------------
# oracle
# 连接数据库host
host_orc=ip
# 连接数据库port
port_orc=1521
# 连接数据库库名
database_orc=dbname
# 用户
user_orc=username
# 密码
password_orc=password
# 字符集
nencoding_orc=utf8
# --------------------------------------------------------------
# sqlserver
# 连接数据库host
host_ms=ip
# 连接数据库port
port_ms=1433
# 连接数据库库名
database_ms=dbname
# 用户
user_ms=username
# 密码
password_ms=password
# 字符集
charset_ms=utf8
# --------------------------------------------------------------
# sqlite3
# 连接数据库文件名,sqlite不支持加密,不使用用户名和密码
database_sqlite3=path/to/your/dbname.db
# --------------------------------------------------------------
# hbase
# 连接数据库host
host_hb=ip
# 连接数据库port,phoenixdb连接使用8765端口而非2181等其他端口
port_hb=8765
# 用户
user_hb=username
# 密码
password_hb=password
然后,准备一份读取properties文件的工具类,姑且称为PropertiesUtil.py,可以寻找网上的,也可以参考我写的。
# -*- coding:utf-8 -*-
class PropertiesUtil(object):
# 缓存配置
__file_dict = {}
def get_config_dict(self, file_path="pdbc.properties"):
"""
获取资源文件,形成字典
:param file_path: 文件路径
:return:字典内容的key、value均为字符串
"""
if file_path not in self.__file_dict:
properties = {}
with open(file_path, 'r', encoding='UTF-8') as pro_file:
for line in pro_file.readlines():
line = line.strip().replace('\n', '')
if line.find('=') > 0 and not line.startswith('#'):
strs = line.split('=')
value = line[len(strs[0]) + 1:]
self.__get_dict(strs[0].strip(), properties, value.strip())
self.__file_dict[file_path] = properties
return self.__file_dict[fil