Answer the question
In order to leave comments, you need to log in
How to connect to the database 1 time?
Hello!
I began to often use database queries in functions, and it turns out that in each new function there is a new connection to the database. I want to make sure that the connection occurs 1 time and after that it is used in the function. Here's what I got, but it doesn't work. Help me please. (DB consists of 1 number column)
import sqlite3
db = sqlite3.connect('base.db')
cursor = db.cursor()
def add(cursor):
a = 1
cursor.execute('INSERT INTO base(number) VALUES("{}")'.format(a))
def change(cursor):
...
add(cursor)
Answer the question
In order to leave comments, you need to log in
Due to the fact that the parameter is named the same as the global variable, this does not work.
Approximately it should be like this:
UPD: the example has been fixed, thanks to MinTnt for your attention
import sqlite3
db = sqlite3.connect('base.db')
cursor = db.cursor()
def add():
a = 1
cursor.execute('INSERT INTO base(number) VALUES("{}")'.format(a))
def change():
pass
add()
import sqlite3
def add(cursor):
a = 1
cursor.execute('INSERT INTO base(number) VALUES("{}")'.format(a))
def change(cursor):
pass
if __name__ == "__main__":
db = sqlite3.connect('base.db')
cursor = db.cursor()
add(cursor)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question