Answer the question
In order to leave comments, you need to log in
Error: connection already closed. What is the reason?
Good day.
I have some shitty code where I am trying to sql INSERT into a table.
I do all this shit through try->except->finally.
Here is the code:
try:
connection = None
connection = conn
cursor = connection.cursor()
cursor.execute('SELECT user_id FROM users WHERE user_id = %s', [user.id])
result_user_id = [x[0] for x in cursor.fetchall()]
if user_id not in result_user_id:
sql_insert = 'INSERT INTO users(user_id, first_name, last_name) VALUES(%s, %s, %s)'
val = (user_id, first_name, last_name)
cursor.execute(sql_insert, val)
connection.commit()
cursor.close()
except (Exception, psycopg2.Error) as error:
print(error)
finally:
if connection is not None:
connection.close()
Answer the question
In order to leave comments, you need to log in
Solved the problem by using "with" instead of try->except->finally.
Even removed cursor.close() because "with" will automatically close itself.
The code:
try:
with conn.cursor() as cursor:
cursor.execute('SELECT user_id FROM users WHERE user_id = %s', [user.id])
result_user_id = [x[0] for x in cursor.fetchall()]
if user_id not in result_user_id:
sql_insert = 'INSERT INTO users(user_id, first_name, last_name) VALUES(%s, %s, %s)'
val = (user_id, first_name, last_name)
cursor.execute(sql_insert, val)
conn.commit()
except (Exception, psycopg2.Error) as error:
conn.rollback() # Чтобы откатить все изменения в случае ошибки
print(error)
I do all this shit
People who insult and humiliate
The problem is that you are about to close a connection that is already closed. Since I don’t see all the code, I can suggest this: add connection.close() after cursor.close(), and finally remove it. And most likely it is not necessary to close the cursor before connection.close() (although I'm not sure). And perhaps the first 3 lines in the code are superfluous in try.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question