V
V
Vitaly2017-04-04 08:30:57
Python
Vitaly, 2017-04-04 08:30:57

When should I create and close cursors when working in SQLite?

Welcome all.
I started to understand the principles of working with the Sqlite database in Python. I read a lot of documentation and examples, but I can not understand such a thing. When do I need to create a database connection, create cursors for SQL queries, and when do I need to close all this?
There is conditionally such a code (Bot in Telegram):

connection = sqlite3.connect('users_db.sqlite', check_same_thread=False)
bot = telebot.TeleBot('bla-bla')

def create_database():

    cursor = connection.cursor()
    cursor.execute("""CREATE TABLE IF NOT EXISTS users(
                      t_id TEXT PRIMARY KEY NOT NULL,
                      username TEXT,
                      first_name TEXT,
                      last_name TEXT,
                      _group TEXT) WITHOUT ROWID""")

    connection.commit()
    cursor.close()


def get_user_group(user_id):
    cursor = connection.cursor()
    cursor.execute("""SELECT _group FROM users WHERE t_id=?""", (user_id,))
    connection.commit()
    user_group = cursor.fetchone()
    cursor.close()
    if not user_group:
        return False
    return user_group[0]


def add_or_update_user_to_db(chat, group):

    if not get_user_group(chat.id):

        cursor = connection.cursor()
        cursor.execute("""INSERT INTO users (t_id, username, first_name, last_name, _group) VALUES (?, ?, ?, ?, ?)""",
                       (chat.id, chat.username, chat.first_name, chat.last_name, group))
        connection.commit()
        cursor.close()

    else:
        cursor = connection.cursor()
        cursor.execute("""UPDATE users SET _group=? WHERE t_id=?""", (group, chat.id))
        connection.commit()
        cursor.close()

@bot.message_handler(content_types=["text"])
def main_menu(message):

    #  тут условно обработка сообщений

if __name__ == '__main__':

    create_database()

    bot.polling(none_stop=True, interval=2)  #  бесконечный цикл

I created a "global" connection, and I use it while the program is running, but it doesn't close anywhere.
Also, every time I access the database, I create a new cursor, make a request, and immediately close the cursor.
Does it make sense to constantly create new cursors, or is it possible to create one next to the connection? And did I do the right thing by creating one connection that doesn't close in any way? In the calculation that the program should be spinning all the time without interruptions.
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sly_tom_cat ., 2017-04-04
@Sly_tom_cat

It is better to close cursors immediately as they are no longer needed and, as far as I remember, you can work with them in the with construction (there is automatic closure).
Something like

with connection.cursor() as cursor:
     do_something_with(cursor)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question