首页 > 代码库 > Python 频繁读取Mysql相关问题

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 True13  14     def select(self):15         self.cursor.execute(self.sql)16         alldata =http://www.mamicode.com/ self.cursor.fetchall()17         self.cursor.close()18         self.conn.close()19         return alldata20  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

 

Python 频繁读取Mysql相关问题