[Python] python对MySqldb模块的简单封装代码 →→→→→进入此内容的聊天室

来自 , 2019-07-07, 写在 Python, 查看 101 次.
URL http://www.code666.cn/view/0b9e57c4
  1. #!/usr/local/python/bin
  2. # coding=utf-8
  3.  
  4. '''Implements a simple database interface
  5.  
  6. Example 0: Create connection:
  7.  
  8.    # Set auto commit to false
  9.    db = DB(False, host = 'x', user = 'x', passwd = 'x', db = 'x')
  10.  
  11. Example 1: Select SQL
  12.  
  13. a. Select the first two rows from ip table:
  14.  
  15.    # normal select
  16.    db.select('select * from ip limit 2')
  17.    # add a where condition:
  18.    db.select('select * from ip where name != %s limit 2', ('0'))
  19.  
  20. b. Select all results but get only the first two:
  21.  
  22.    db.execute('select * from ip')
  23.    # get dict rows
  24.    db.get_rows(2, is_dict = True)
  25.  
  26. Example 2: Insert/Replace SQL
  27.  
  28. a. Insert a new record into ip table:
  29.  
  30.    db.insert('ip', {'address':'192.168.0.1', 'name': 'vm-xxx'})
  31.    db.commit()
  32.  
  33. b. Insert multi-records into ip table:
  34.  
  35.    db.multi_insert('ip', ('address','name'), [('192.168.0.1', 'vm-xxx'),
  36.        ('192.168.0.2', 'vm-yyy'), ('192.168.0.3', 'vm-zzz')])
  37.    db.commit()
  38.  
  39. Example 3: Update SQL
  40.  
  41. a. Update the address of row whose name is vm-xxx:
  42.  
  43.    db.update('ip', {'address':'192.168.0.1'}, {'name': 'vm-xxx'})
  44.    db.commit()
  45.  
  46. Example 4: Delete SQL
  47.  
  48. a. Delete the row whose name is 'vm-xxx':
  49.  
  50.    db.delete('ip', {'name': 'vm-xxx'})
  51.    db.commit()
  52. '''
  53.  
  54. # Can be 'Prototype', 'Development', 'Product'
  55. __status__ = 'Development'
  56. __author__ = 'tuantuan.lv <dangoakchan@foxmail.com>'
  57.  
  58. import sys
  59. import MySQLdb
  60.  
  61. from pypet.common import log
  62.  
  63. class DB():
  64.     '''A simple database query interface.'''
  65.     def __init__(self, auto_commit, **kwargs):
  66.         if 'charset' not in kwargs:
  67.             kwargs['charset'] = 'utf8'
  68.  
  69.         self.conn = MySQLdb.connect(**kwargs)
  70.         self.cursor = self.conn.cursor()
  71.         self.autocommit(auto_commit)
  72.  
  73.     def execute(self, sql, args = None):
  74.         return self.cursor.execute(sql, args)
  75.  
  76.     def executemany(self, sql, args):
  77.         '''Execute a multi-row query.'''
  78.         return self.cursor.executemany(sql, args)
  79.  
  80.     def select(self, sql, args = None):
  81.         self.execute(sql, args)
  82.         return self.get_rows()
  83.  
  84.     def insert(self, table, column_dict):
  85.         keys = '`,`'.join(column_dict.keys())
  86.         values = column_dict.values()
  87.         placeholder = ','.join([ '%s' for v in column_dict.values() ])
  88.         ins_sql = 'INSERT INTO %(table)s (`%(keys)s`) VALUES (%(placeholder)s)'
  89.  
  90.         return self.execute(ins_sql % locals(), values)
  91.  
  92.     def multi_insert(self, sql, args):
  93.         '''Execute a multi-row insert, the same as executemany'''
  94.         return self.cursor.executemany(sql, args)
  95.  
  96.     def replace(self, table, column_dict):
  97.         keys = '`,`'.join(column_dict.keys())
  98.         values = column_dict.values()
  99.         placeholder = ','.join([ '%s' for v in column_dict.values() ])
  100.         repl_sql = 'REPLACE INTO %(table)s (`%(keys)s`) VALUES (%(placeholder)s)'
  101.  
  102.         return self.execute(repl_sql % locals(), values)
  103.  
  104.     def update(self, table, column_dict, cond_dict):
  105.         set_stmt = ','.join([ '%s=%%s' % k for k in column_dict.keys() ])
  106.         cond_stmt = ','.join([ '%s=%%s' % k for k in cond_dict.keys() ])
  107.         args = column_dict.values() + cond_dict.values()
  108.         upd_sql = 'UPDATE %(table)s set %(set_stmt)s where %(cond_stmt)s'
  109.  
  110.         return self.execute(upd_sql % locals(), args)
  111.  
  112.     def delete(self, table, cond_dict):
  113.         cond_stmt = ','.join([ '%s=%%s' % k for k in cond_dict.keys() ])
  114.         del_sql = 'DELETE FROM %(table)s where %(cond_stmt)s'
  115.  
  116.         return self.execute(del_sql % locals(), cond_dict.values())
  117.  
  118.     def get_rows(self, size = None, is_dict = False):
  119.         if size is None:
  120.             rows = self.cursor.fetchall()
  121.         else:
  122.             rows = self.cursor.fetchmany(size)
  123.  
  124.         if rows is None:
  125.             rows = []
  126.  
  127.         if is_dict:
  128.             dict_rows = []
  129.             dict_keys = [ r[0] for r in self.cursor.description ]
  130.  
  131.             for row in rows:
  132.                 print row, dict_keys
  133.                 print zip(dict_keys, row)
  134.                 dict_rows.append(dict(zip(dict_keys, row)))
  135.  
  136.             rows = dict_rows
  137.  
  138.         return rows
  139.  
  140.     def get_rows_num(self):
  141.         return self.cursor.rowcount
  142.  
  143.     def get_mysql_version(self):
  144.         MySQLdb.get_client_info()
  145.  
  146.     def autocommit(self, flag):
  147.         self.conn.autocommit(flag)
  148.  
  149.     def commit(self):
  150.         '''Commits the current transaction.'''
  151.         self.conn.commit()
  152.  
  153.     def __del__(self):
  154.         #self.commit()
  155.         self.close()
  156.  
  157.     def close(self):
  158.         self.cursor.close()
  159.         self.conn.close()
  160.  
  161. # vim: set expandtab smarttab shiftwidth=4 tabstop=4:
  162. #//python/5320

回复 "python对MySqldb模块的简单封装代码"

这儿你可以回复上面这条便签

captcha