1、连接本机数据库
def __init__(self):
self.host = 'localhost'
self.port = 3306 # 端口号
self.user = 'root' # 用户名
self.password = "123456" # 密码
self.db = "character" # 库
self.table = "hanzi" # 表
self.file = open('log.txt', 'a')
# 链接数据库
def connectMysql(self):
try:
self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user,
passwd=self.password, db=self.db, charset='utf8')
self.cursor = self.conn.cursor()
except:
print('connect mysql error.')
2、通过ssh连接外部数据库
def __init__(self):
self.host = '127.0.0.1'
self.port = 3306 # 端口号
self.user = 'root' # 用户名
self.password = "xxxxxxxx" # 数据库密码
self.db = "character" # 库
self.table = "hanzi" # 表
self.file = open('log.txt', 'a')
# 链接数据库
def connectMysql(self):
self.server = SSHTunnelForwarder(
ssh_address_or_host = ('47.105.xxx.xxx', 22),
ssh_username = 'root',
ssh_password = 'xxxxxxxx', #服务器密码
remote_bind_address = ('127.0.0.1', 3306)
)
print(self.server.start())
print(self.server.local_bind_port)
#主要是要链接ssh服务器在本地的port.
try:
self.conn = pymysql.connect(host=self.host, port=self.server.local_bind_port, user=self.user,
passwd=self.password, db=self.db, charset='utf8')
self.cursor = self.conn.cursor()
except:
print('connect mysql error.')
self.cursor.close()
self.conn.close()
self.server.close()