简体   繁体   English

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

[英]Does the way of database connection, opening and closing in python affect the performance of the code?

I am using the code below in a loop which is excecuted several times. 我正在循环执行以下循环中的以下代码。 I doubt that in the end of the code, creating and closing the database in an inappropriate way which slows down the performance of the program. 我怀疑在代码的最后,是否以不合适的方式创建和关闭数据库,从而降低了程序的性能。 Do i have to open, create cursors and close the connection everytime? 我是否每次都要打开,创建游标并关闭连接?

"""
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()

This is not really a SQL question. 这实际上不是SQL问题。 However what I do know is this method puts way more strain on your server than other methods. 但是我所知道的是,与其他方法相比,此方法给服务器带来更大的负担。 I doubt it will slow your program down signifiantly, depending on the response time of your servers. 我怀疑这会严重降低程序速度,具体取决于服务器的响应时间。

Is it not possible to grab all of the information at once and store it in in memory within the program? 是否无法一次获取所有信息并将其存储在程序内的内存中?

I don't have experience in python but I would think this should be possible. 我没有python的经验,但我认为这应该可行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM