D
D
di2020-07-24 21:50:45
Python
di, 2020-07-24 21:50:45

Create connection to MYSQL once or create every time?

Let's say I'm writing a telegram bot in python and I need to do something with the database. The connection must be created once, or each time a message is processed.
I consider that it is necessary to create one connection and to hold. for example

bot = telebot.TeleBot("")
db = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="root",
    port="3307",
    database="youtube"
)
db.reconnect(attempts = 100, delay=10)

@bot.message_handler()
def route(message):
    cursor = db.cursor();
    sql = "SELECT * users"
    cursor.execute(sql)
    result = cursor.fetchall()
    db.commit()
    bot.send_message(message.chat.id, "Hello world!")


However, my friend desperately argues that it is necessary to create a connection every time. like this for example.

bot = telebot.TeleBot("")

@bot.message_handler()
def route(message):
      db = mysql.connector.connect(
          host="localhost",
          user="root",
          passwd="root",
          port="3307",
          database="youtube"
      )
     cursor = db.cursor();
     sql = "SELECT * users"
     cursor.execute(sql)
     result = cursor.fetchall()
     db.commit()
     db.close()
     bot.send_message(message.chat.id, "Hello world!")


Which option is correct? Are there any proofs, documentation for this case?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
kirillinyakin, 2020-07-25
@kirillinyakin

In general, MySQL automatically breaks the connection in case of downtime, and as far as I know this can be configured, in my project I create a connection every time and at the end of the function I break

D
di, 2020-07-25
@Delgus

The first option won't work. connect() returns a single connection, not a pool

bot = telebot.TeleBot("")
# создаем пулл из 3 соединений например
cnxpool = mysql.connector.pooling.MySQLConnectionPool(pool_name = "mypool",
                                                      pool_size = 3,
                                                      host="localhost",
    user="root",
    passwd="root",
    port="3307",
    database="youtube")

@bot.message_handler()
def route(message):
    # достаем соединение из пулла
    db = cnxpool.get_connection()
    cursor = db.cursor();
    sql = "SELECT * users"
    cursor.execute(sql)
    result = cursor.fetchall()
    db.commit()
    # закрываем соединение. оно вернется обратно в пулл
    db.close()
    bot.send_message(message.chat.id, "Hello world!")

A new connection, although established quite quickly, still wastes server resources. Spending them many times when you can one is certainly not worth it. so this one is better in my opinion

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question