我想知道是否存在一种有效的方法(可能是全局连接)来创建数据库连接并使用Python执行插入语句。
当前,如果我有大约1000条insert语句,我将创建1000个db连接并将数据推送到表中。以下是 每个插入语句调用的函数
def getSqlCon():
# connection to point to SQL
con = mysql.connector.connect(
user=config.user,
password=config.password,
host=config.host,
database=config.database
)
return con
def write_to_sql(query):
result = None
# Running in loop to avoid write issue due to db conn problem
for i in range(0, 5):
try:
# Calling getAWS to get connceted to db
con = getSqlCon()
# Opens a db to perform operations
cur = con.cursor()
# Execute the query 'query'
cur.execute(query)
con.commit()
# Closing the db connection
cur.close()
con.close()
#print("Data Inserted")
result = 1
break
except Exception as e:
print("ERROR IN WRITE SQL. RETRYING IN 5 SEC")
time.sleep(5)
continue
return result
这种方法现在成为瓶颈,并降低了性能。同样,很多时候,这会导致连接限制错误。 请让我知道是否有更好的解决方案来解决这个问题。