mysql连接

5hcedyr0  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(241)

我还是个新手。
我可以用ssh凭据连接到我的远程数据库,但是。。。
希望防止此错误发生在正在刮取的每个项目上。
错误:2055:在“127.0.0.1:3306”处与mysql服务器失去连接,系统错误:10053已建立的连接被主机中的软件中止
下面是我的mysql管道对象

import mysql.connector
import sshtunnel

class MySQLStorePipeline(object):

def __init__(self):
    with sshtunnel.SSHTunnelForwarder(
        ('13.***.***.***', 22),
        ssh_username='***',
        ssh_password='***',
        remote_bind_address=('db1.prod.***.***.net.***', 3306),
        local_bind_address=('127.0.0.1', 3306)
    ) as tunnel:

        self.dbcon = mysql.connector.connect(
            host='127.0.0.1', 
            port=3306,
            user='***', 
            database='***', 
            password='***',
            charset='utf8'
        )
        self.cursor = self.dbcon.cursor() 

def process_item(self, item, spider):
    try:
        tables = self.cursor.execute('SHOW TABLES')
        print tables.fetchall()

        self.dbcon.commit()            
    except mysql.connector.Error as err:
        print('Error: {}'.format(err))

    return item

我只是不知道如何在process\u item函数中维护数据库连接

vd8tlhqk

vd8tlhqk1#

你用的是 with ... 这就是为什么python的ssh隧道会自动关闭的原因

相关问题