H
H
hardwellZero2015-05-14 18:33:48
MySQL
hardwellZero, 2015-05-14 18:33:48

How to implement a reconnect to the database every N seconds?

Good evening.
There is this function:

def __init__(self):
        ''' creates a connection at the initialization moment
        and also a cursor used later '''
 
        try:
            # creates a connection
            self.conn = MySQLdb.connect(  host = self.dbhost,
                                        port = self.dbport,
                                        user = self.dbuser,
                                        passwd = self.dbpass
                                    )
            self.cursor = self.conn.cursor()
        except MySQLdb.Error, e:
            print "Error %d: %s" % (e.args[0], e.args[1])
            
            sys.exit (1)

Now I want to implement it in such a way that if there is a connection error, after 5 seconds a reconnect occurs and so on in a circle until a successful connection.
How can you screw this up? I saw how it was implemented with the number of attempts, but this is not it.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
Melkij, 2015-05-14
@hardwellZero

What is the problem? Loop the code instead of exit according to the established connection
success condition

A
Alexey Volegov, 2015-05-14
@EagleMoor

while (1 == 1) did someone cancel?

D
Dmitry Demidov, 2015-05-14
@ptitca_zu

Something like this:

def __init__(self):
    while True:
        ''' creates a connection at the initialization moment
        and also a cursor used later '''
 
        try:
            # creates a connection
            self.conn = MySQLdb.connect(  host = self.dbhost,
                                        port = self.dbport,
                                        user = self.dbuser,
                                        passwd = self.dbpass
                                    )
            self.cursor = self.conn.cursor()
            break
        except MySQLdb.Error, e:
            print "Error %d: %s" % (e.args[0], e.args[1])
            time.sleep(5)

V
Vladimir Abramov, 2015-05-14
@kivsiak

How about a bike?
docs.sqlalchemy.org/en/latest/core/pooling.html or
dev.mysql.com/doc/connector-python/en/connector-py... what's wrong?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question