zoukankan      html  css  js  c++  java
  • 自己写的Python数据库连接类和sql语句拼接方法

    这个工具类十分简单和简洁。

    sql拼接方法

    # encoding=utf-8
    from django.http import HttpResponse
    from anyjson import serialize
    from django.http import HttpResponse
    from anyjson import serialize
    import MySQLdb
    
    
    def safe(s):
        return MySQLdb.escape_string(s)
    
    
    def get_i_sql(table, dict):
        '''
        生成insert的sql语句
        @table,插入记录的表名
        @dict,插入的数据,字典
        '''
        sql = 'insert into %s set ' % table
        sql += dict_2_str(dict)
        return sql
    
    
    def get_s_sql(table, keys, conditions, isdistinct=0):
        '''
            生成select的sql语句
        @table,查询记录的表名
        @key,需要查询的字段
        @conditions,插入的数据,字典
        @isdistinct,查询的数据是否不重复
        '''
        if isdistinct:
            sql = 'select distinct %s ' % ",".join(keys)
        else:
            sql = 'select  %s ' % ",".join(keys)
        sql += ' from %s ' % table
        if conditions:
            sql += ' where %s ' % dict_2_str_and(conditions)
        return sql
    
    
    def get_u_sql(table, value, conditions):
        '''
            生成update的sql语句
        @table,查询记录的表名
        @value,dict,需要更新的字段
        @conditions,插入的数据,字典
        '''
        sql = 'update %s set ' % table
        sql += dict_2_str(value)
        if conditions:
            sql += ' where %s ' % dict_2_str_and(conditions)
        return sql
    
    
    def get_d_sql(table, conditions):
        '''
            生成detele的sql语句
        @table,查询记录的表名
    
        @conditions,插入的数据,字典
        '''
        sql = 'delete from  %s  ' % table
        if conditions:
            sql += ' where %s ' % dict_2_str_and(conditions)
        return sql
    
    
    def dict_2_str(dictin):
        '''
        将字典变成,key='value',key='value' 的形式
        '''
        tmplist = []
        for k, v in dictin.items():
            tmp = "%s='%s'" % (str(k), safe(str(v)))
            tmplist.append(' ' + tmp + ' ')
        return ','.join(tmplist)
    
    
    def dict_2_str_and(dictin):
        '''
        将字典变成,key='value' and key='value'的形式
        '''
        tmplist = []
        for k, v in dictin.items():
            tmp = "%s='%s'" % (str(k), safe(str(v)))
            tmplist.append(' ' + tmp + ' ')
        return ' and '.join(tmplist)

    数据库连接类

    class SqlConn():
        def __init__(self):
            self.conn= DBpool.pool.connection()
            self.cur=self.conn.cursor()
        def cur(self):
            return self.cur()
        def commit(self):
            self.conn.commit()
        def execute(self,sql,fetchone=0):
            self.cur.execute(sql)
            return self.cur.fetchone() if fetchone else self.cur.fetchall()
        def last_id(self,table):
            sql='SELECT LAST_INSERT_ID() from %s'%table
            return self.execute(sql,1)[0]
        def close(self):
            self.cur.close()
            self.conn.close()

    self.conn= DBpool.pool.connection()
    中,我用的是连接池连接,这里可以改成普通的数据库连接

    查询结果解析方法

    def fSqlResult(r,key_list):
        #r @tuple 数据库fetchall的结果
        #key_list @list 查询字段的keys
        # format SQL Result 格式化数据库查询的结果,转化成包含多个字典的列表格式,即((1,2),(3,4))->[{"key1":1,"key2":2},{"key1":3,"key2":4}]
        #返回 @dict 查询结果
        mlist=[]
        l=len(key_list)
        if r:
            for item in r:
                tmp={}
                for i in range(l):
                    tmp[key_list[i]]=str(item[i])
                mlist.append(tmp)
        return mlist

    使用方法:

    例如要执行sql语句:select username,pwd,type,age,birth from user where username='abc';

    conn=SqlConn()
    key_list=['username','pwd','type','age','birth']
    sql=s_sql('user',key_list,{'username':'abc'}
    r=conn.execute(sql)
    data=fSqlResult(r,key_list)
    conn.close()

    data的格式为[{'username':'i am username','pwd':'i am pwd','type':'student','age':12,'birth':'2014-7-2'}]
    方便快捷,适用于经常需要用到数据库的CRUD连接的应用。

  • 相关阅读:
    android app记录执行日志 捕获奔溃异常 ,存储日志到文件
    对扩展openflow协议的一点思考
    Echarts柱状图
    python实现插入排序
    MyBatis -- 对表进行增删改查(基于注解的实现)
    pat解题报告【1082】
    [Swift]LeetCode974. 和可被 K 整除的子数组 | Subarray Sums Divisible by K
    [Swift]LeetCode976. 三角形的最大周长 | Largest Perimeter Triangle
    [Swift]LeetCode345. 反转字符串中的元音字母 | Reverse Vowels of a String
    [Swift]LeetCode343. 整数拆分 | Integer Break
  • 原文地址:https://www.cnblogs.com/Xjng/p/3821827.html
Copyright © 2011-2022 走看看