W
W
Whey2019-06-25 17:45:03
MySQL
Whey, 2019-06-25 17:45:03

How to avoid closing the connection to the database if the connection is made from another library?

I have a main program - main.py - that needs to connect to a database and then perform actions.
Here is a piece of code from main.py:

from ConnectToDB import db
    def authorization(self):
        self.mycursors = db()
        self.mycursors.execute("SELECT * FROM `users` WHERE `VK_ID` LIKE '111'")

And also I have a library in which the connection occurs:
import mysql.connector

def db():
    mydb = mysql.connector.connect(
                        host="localhost",
                        user="root",
                        passwd="",
                        database="vk-bot"
                    )
    cursor = mydb.cursor()
    return cursor

Naturally, after calling the library, the connection is closed, and I cannot perform any actions. How can such a closure be avoided, and what can be done? It is not rational to add a connection function to main.py, because in other modules there will be a connection to the database.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Belyaev, 2019-06-25
@Whey

In mysql itself, you can set a large wait_timeout in the config, but this is not really an option ...
In the same php, there is a mysqli_ping function or something like that, I also had a script hanging for months and occasionally catching a request, it began to process it working with the database, of course, the connection no matter what timeout you specify, and very large timeouts at the server lead to hanging connections that are not closed, therefore, in your program, consider such a moment in the layer to the database to remember the time of the last access to the database and if it exceeds, for example, 2 minutes, then check the connection and if it is not there, then reconnect.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question