- 論壇徽章:
- 1
|
CU上大神挺多,貼幾段代碼給大神們?cè)u(píng)審一下。
因?yàn)榇笊駛円姸嘧R(shí)廣,目的就是把這幾段雖然簡單,但是卻很基礎(chǔ)、使用很頻繁的代碼給優(yōu)化到極致,性能達(dá)到最好:
第一段:一個(gè)數(shù)據(jù)庫操作封裝,目的就是一個(gè)方法完成所有數(shù)據(jù)庫相關(guān)的操作。
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- import mysql.connector
- import mysql.connector.pooling
- import mysql.connector.cursor
- class Db(object):
- def __init__(self, config, pool_name=None, pool_size=5):
- self.pool = mysql.connector.pooling.MySQLConnectionPool(
- pool_name=pool_name,
- pool_size=pool_size,
- **config)
- def get_connection(self):
- return self.pool.get_connection()
- def execute(self, sql, params=None):
- conn = self.get_connection()
- cursor = conn.cursor(buffered=True, cursor_class=MySQLDictCursor)
- data_set = []
- for result in cursor.execute(sql, params, multi=True):
- if result.with_rows:
- data_set.append(result.fetchall())
- else:
- data_set.append(None)
- conn.commit()
- cursor.close()
- conn.close()
- return data_set
- class MySQLDictCursor(mysql.connector.cursor.MySQLCursor):
- def _row_to_python(self, row_data, desc=None):
- row = super(MySQLDictCursor, self)._row_to_python(row_data, desc)
- if row:
- return dict(zip(self.column_names, row))
- return None
復(fù)制代碼 |
|