Python 頻繁讀取Mysql相關問題


1、需要頻繁select大量數據,時間長、消耗內存大,如何解決mysql性能問題?

如果對返回的結果數量沒有要求,可以控制返回的數量:

cursor.fetchmany(size=1000)

這樣是只返回1000條數據,如果返回的結果小於size,則返回所有數據;

如果你只需要一條,則更簡單:fetchone()

2、每次插入的數據過大,MySQL server has gone away 如何解決?

存儲為blob類型;

修改my.conf里:max_allowed_packet = 500m

3、要把python的list類型存入mysql,然后下次還需要以list格式讀取,如何操作?

因為list類型里包含半角的逗號,或插入的數據里包含特殊符號,則不能正常插入mysql。

Google里有很多方法,我采取的是base64。將要插入的數據base64 encode可以正常存入Mysql。

base64str = base64.b64encode(str(mysqlstr))

mysqlstr = base64.b64decode(b64str)

注意:當你讀取的時候,需要base64decode,這時得到的是str,則不能正常使用list序列取值。怎么辦?

eval(string)

如上操作,eval可以很好的解決這個問題,把str變成tuple,就可以直接用了。

4、頻繁操作Mysql更刪查數據時,最好采用多線程操作數據庫,避免因為my.conf配置問題帶來的麻煩。

下面是一個Mysql多線程操作類:

 1 class MYSQL:
 2     def __init__(self,sql):
 3         self.sql = sql
 4         self.conn = MySQLdb.connect(charset='utf8',user='yourname',passwd='passwd',db='your dbname')            
 5         self.cursor = self.conn.cursor()
 6  
 7     def insert(self):
 8         self.cursor.execute(self.sql)
 9         self.conn.commit()
10         self.cursor.close()
11         self.conn.close()
12         return True
13  
14     def select(self):
15         self.cursor.execute(self.sql)
16         alldata = self.cursor.fetchall()
17         self.cursor.close()
18         self.conn.close()
19         return alldata
20  
21     def update(self):
22         self.cursor.execute(self.sql)
23         self.conn.commit()
24         self.cursor.close()
25         self.conn.close()
26         return True

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM