首页 > 数据库技术 > 详细

python使用单例模式创建MySQL链接

时间:2018-09-16 10:55:35      阅读:418      评论:0      收藏:0      [点我收藏+]

代码:

from functools import wraps
import mysql.connector
from sshtunnel import SSHTunnelForwarder


def singleton(cls):
    instances = {}

    @wraps(cls)
    def get_instance(*args, **kw):
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]
    return get_instance


# 数据库连接实例
@singleton
class MySQLSingle(object):
    def __init__(self, conn=‘‘, server=‘‘):
        self.conn = conn
        self.server = server

    def get_conn(self, host_jump, port_jump, ssh_pk_jump, user_name_jump, host_mysql, port_mysql, user_name_mysql, password_mysql, database):
        try:
            self.server = SSHTunnelForwarder(
                (host_jump, int(port_jump)),  # 跳板机的配置
                ssh_pkey=ssh_pk_jump,
                ssh_username=user_name_jump,
                remote_bind_address=(host_mysql, int(port_mysql)))  # 数据库服务器的配置
            self.server.start()
            self.conn = mysql.connector.connect(host=127.0.0.1, port=self.server.local_bind_port, user=user_name_mysql,
                                           password=password_mysql, database=database)
        except Exception as e:
            print(File to connect database: %s % e)
        return self.conn, self.server

使用方法如下:

mysql_single = MySQLSingle()
conn, server = mysql_single.get_conn(host_jump, port_jump, ssh_pk_jump, user_name_jump, host_mysql, port_mysql,
                                     user_name_mysql, password_mysql, database)
# do something...
conn.close()
server.close()

 

python使用单例模式创建MySQL链接

原文:https://www.cnblogs.com/gide/p/9654945.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!