自己写的Python数据库连接类和sql语句拼接方法
2023-09-14 09:12:28 时间
这个工具类十分简单和简洁。
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连接的应用。
相关文章
- python求逆矩阵的方法,Python 如何求矩阵的逆「建议收藏」
- python skitlearn_Python sklearn
- python要不要装pycharm-Python和pyCharm安装
- python实现矩阵的转置_Python实现矩阵转置的方法分析
- python中pygame怎么安_Python中pygame安装方法图文详解
- Python数据库同步神器(一键同步)
- python整除和取余写法_Python的整除和取余[通俗易懂]
- Python使用技巧之MySQL数据库增删改查操作
- 【说站】Python操作PgSQL数据库的方法
- 经纬度距离计算 python_Python已知两坐标求距离
- Python错误:“数据库引擎找不到输入表或查询”的一种可能情况
- python-数据库编程-如何在Python中连接到数据库
- python-Python与MySQL数据库-使用Python执行MySQL查询
- python-Python与SQLite数据库-SQLite数据库的基本知识(一)
- python-Python与SQLite数据库-处理SQLite查询结果(二)
- python-Python与MongoDB数据库-使用Python执行MongoDB查询(一)
- python-Python与MongoDB数据库-处理MongoDB查询结果
- python-数据库编程-如何处理错误和异常(一)
- Python访问数据库——学习笔记详解编程语言
- Linux创建Python文件的步骤(linux新建python文件)
- Linux查看Python版本的有效方法(linux查看python版本)
- Python驱动Oracle数据库(python操作oracle)
- 使用Python连接SQL Server数据库(python连接sqlserver)
- Python轻松连接SQL Server数据库(python连接sqlserver)
- 从 Python 连接到 MySQL:实现更多强大的数据库应用(python和mysql)
- Python与Linux:开启互联网信息技术时代(python和linux)
- python连接MySQL、MongoDB、Redis、memcache等数据库的方法