python中的数据库连接、打开和关闭方式是否影响代码的性能?

2024-09-30 22:14:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个循环中使用下面的代码,这个循环被执行了好几次。我怀疑在代码的最后,以不适当的方式创建和关闭数据库会降低程序的性能。我是否每次都要打开、创建光标和关闭连接?你知道吗

"""
Connecting to Database and putting data into in
"""

db= MySQLdb.connect("localhost","root","xxxx","Data")
cursor=db.cursor()


#checking phase to stop scrapping

sql = """SELECT Short_link FROM AppartRent WHERE Short_link=%s"""

rows = cursor.execute(sql,(link_result))
print rows

if rows>=1:
duplicate_count+=1
print duplicate_count

if duplicate_count>=100:


print "The program has started getting duplicates now- The program is terminating"
        sys.exit()
else:
    query="""INSERT INTO AppartRent (Sale_Rent, Type, Area, Title,Price, PricePerSqrFt, Bedroom,Agency_Fee, Bathroom, Size,ZonedFor, Freehold, Prop_ref,Furnished_status,Rent_payment,Building_info,Amenities,Trade_name,Licence, RERA_ID,Phone_info,Short_link) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
    cursor.execute(query,(Sale_Rent_result,Type_result,area_result, title_result, price_result, Pricepersq_result, bedroom_result, agencyfee_result, bathroom_result, size_result,Zoned_for_result, Freehold_result, propertyref_result, furnished_result, rent_is_paid_result, building_result, Amenities_result, tradename_result, licencenum_result, reraid_result, phone_result, link_result))


db.commit()
cursor.close()
db.close()

Tags: to代码executedbsqlcountlinkresult
1条回答
网友
1楼 · 发布于 2024-09-30 22:14:31

这不是一个真正的SQL问题。不过,我知道的是,这种方法比其他方法给服务器带来更大的压力。我怀疑它会显着减慢您的程序,这取决于您的服务器的响应时间。你知道吗

不可能一次获取所有信息并将其存储在程序的内存中吗?你知道吗

我没有python方面的经验,但我认为这应该是可能的。你知道吗

相关问题 更多 >