[英]What happen if we use PostgreSQL multiple connection without closing it?
connection.py File connection.py 文件
def create_connection():
connection = psycopg2.connect("dbname=suppliers user=postgres password=postgres")
return connection
def create_cursor():
connection = create_connection()
cursor = connection.cursor()
return cursor
Above example will create a connection 2 times when calling both create_connection() and create_cursor() method当同时调用 create_connection() 和 create_cursor() 方法时,上面的示例将创建连接 2 次
Query File查询文件
def common_query():
sql_query = "INSERT INTO supply VALUES (1, 'test', 'test')"
conn = create_connection()
cursor = create_cursor()
with conn:
with cursor as cur:
cur.execute(sql_query)
conn.close()
Above example will call create_connection and create_cursor method, but as you can see while calling create_connection, connection has already been established and in create_cursor() while calling create_connection() method again it create another connection.上面的示例将调用 create_connection 和 create_cursor 方法,但是正如您在调用 create_connection 时看到的那样,连接已经建立,并且在 create_cursor() 中再次调用 create_connection() 方法时它会创建另一个连接。
So while execution query it does't show any error nor it insert my data into database.因此,在执行查询时它不会显示任何错误,也不会将我的数据插入数据库。 Let me know whats happened in it?
让我知道里面发生了什么?
You create two connections for each call to common_query.您为每次调用 common_query 创建两个连接。 One is explicitly closed, the other is closed at some point because it went out of scope. (Python is a garbage collected language)
一个是显式关闭的,另一个是在某个时候关闭的,因为它超出了 scope。(Python 是一种垃圾收集语言)
You don't commit on either one, so whatever work you did gets rolled back automatically.你不提交任何一个,所以你所做的任何工作都会自动回滚。 This is unrelated to the first point.
这与第一点无关。 The same thing would happen if you had only created one connection (and also didn't commit on it).
如果您只创建了一个连接(并且也没有提交),同样的事情也会发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.