Python Sql数据库增删改查操作简单封装


Posted in Python onApril 18, 2016

本文实例为大家分享了如何利用Python对数据库的增删改查进行简单的封装,供大家参考,具体内容如下

1.insert    

import mysql.connector
import os
import codecs
#设置数据库用户名和密码
user='root';#用户名
pwd='root';#密码
host='localhost';#ip地址
db='mysql';#所要操作数据库名字
charset='UTF-8'
cnx = mysql.connector.connect(user=user,password=pwd, host=host, database=db)
#设置游标
cursor = cnx.cursor(dictionary=True)
#插入数据
#print(insert('gelixi_help_type',{'type_name':'\'sddfdsfs\'','type_sort':'283'}))
def insert(table_name,insert_dict):
  param='';
  value='';
  if(isinstance(insert_dict,dict)):
    for key in insert_dict.keys():
      param=param+key+","
      value=value+insert_dict[key]+','
    param=param[:-1]
    value=value[:-1]
  sql="insert into %s (%s) values(%s)"%(table_name,param,value)
  cursor.execute(sql)
  id=cursor.lastrowid
  cnx.commit()
  return id

2.delete    

def delete(table_name,where=''):
  if(where!=''):
    str='where'
    for key_value in where.keys():
      value=where[key_value]
      str=str+' '+key_value+'='+value+' '+'and'
    where=str[:-3]
    sql="delete from %s %s"%(table_name,where)
    cursor.execute(sql)
    cnx.commit()

3.select    

#取得数据库信息
# print(select({'table':'gelixi_help_type','where':{'help_show': '1'}},'type_name,type_id'))
def select(param,fields='*'):
  table=param['table']
  if('where' in param):
    thewhere=param['where']
    if(isinstance (thewhere,dict)):
      keys=thewhere.keys()
      str='where';
      for key_value in keys:
        value=thewhere[key_value]
        str=str+' '+key_value+'='+value+' '+'and'
      where=str[:-3]
  else:
    where=''
  sql="select %s from %s %s"%(fields,table,where)
  cursor.execute(sql)
  result=cursor.fetchall()
  return result

4.showtable,showcolumns    

#显示建表语句
#table string 表名
#return string 建表语句
def showCreateTable(table):
  sql='show create table %s'%(table)
  cursor.execute(sql)
  result=cursor.fetchall()[0]
  return result['Create Table']
#print(showCreateTable('gelixi_admin'))
#显示表结构语句
def showColumns(table):
  sql='show columns from %s '%(table)
  print(sql)
  cursor.execute(sql)
  result=cursor.fetchall()
  dict1={}
  for info in result:
    dict1[info['Field']]=info
  return dict1

以上就是Python Sql数据库增删改查操作的相关操作,希望对大家的学习有所帮助。

Python 相关文章推荐
python实现类的静态变量用法实例
May 08 Python
Python爬虫实例_利用百度地图API批量获取城市所有的POI点
Jan 10 Python
Python cookbook(数据结构与算法)从任意长度的可迭代对象中分解元素操作示例
Feb 13 Python
解决python nohup linux 后台运行输出的问题
May 11 Python
python验证码识别教程之滑动验证码
Jun 04 Python
详解Selenium+PhantomJS+python简单实现爬虫的功能
Jul 14 Python
django-rest-framework解析请求参数过程详解
Jul 18 Python
Python3离线安装Requests模块问题
Oct 13 Python
python飞机大战pygame游戏框架搭建操作详解
Dec 17 Python
python 异步async库的使用说明
May 04 Python
Django框架安装及项目创建过程解析
Sep 14 Python
Django如何使用asyncio协程和ThreadPoolExecutor多线程
Oct 12 Python
python使用paramiko实现远程拷贝文件的方法
Apr 18 #Python
python UNIX_TIMESTAMP时间处理方法分析
Apr 18 #Python
python动态加载包的方法小结
Apr 18 #Python
python实现按行切分文本文件的方法
Apr 18 #Python
Python获取linux主机ip的简单实现方法
Apr 18 #Python
Python实现递归遍历文件夹并删除文件
Apr 18 #Python
Python简单实现TCP包发送十六进制数据的方法
Apr 16 #Python
You might like
php使用strtotime和date函数判断日期是否有效代码分享
2013/12/25 PHP
thinkPHP模板中for循环与switch语句用法示例
2016/11/30 PHP
thinkphp 抓取网站的内容并且保存到本地的实例详解
2017/08/25 PHP
PHP使用星号替代用户名手机和邮箱的实现代码
2018/02/07 PHP
详解Laravel服务容器的绑定与解析
2019/11/05 PHP
ExtJs事件机制基本代码模型和流程解析
2010/10/24 Javascript
输入框的字数时时统计—关于 onpropertychange 和 oninput 使用
2011/10/21 Javascript
javascript常用方法汇总
2014/12/02 Javascript
使用jQueryMobile实现滑动翻页效果的方法
2015/02/04 Javascript
JavaScript动态提示输入框输入字数的方法
2015/07/27 Javascript
jQuery焦点图切换特效代码分享
2015/09/15 Javascript
jquery实现可自动判断位置的弹出层效果代码
2015/10/12 Javascript
scroll事件实现监控滚动条并分页显示(zepto.js)
2016/12/18 Javascript
vue+vue-router转场动画的实例代码
2018/09/01 Javascript
Vue中android4.4不兼容问题的解决方法
2018/09/04 Javascript
详解webpack模块加载器兼打包工具
2018/09/11 Javascript
手把手教你使用TypeScript开发Node.js应用
2019/05/06 Javascript
VuePress 中如何增加用户登录功能
2019/11/29 Javascript
[03:37]2014DOTA2国际邀请赛 主赛事第一日胜者组TOPPLAY
2014/07/19 DOTA
python网络编程学习笔记(八):XML生成与解析(DOM、ElementTree)
2014/06/09 Python
用python登录Dr.com思路以及代码分享
2014/06/25 Python
PyCharm安装第三方库如Requests的图文教程
2018/05/18 Python
python实现可视化动态CPU性能监控
2018/06/21 Python
python无限生成不重复(字母,数字,字符)组合的方法
2018/12/04 Python
在PyCharm导航区中打开多个Project的关闭方法
2019/01/17 Python
Python 实现域名解析为ip的方法
2019/02/14 Python
python实现单目标、多目标、多尺度、自定义特征的KCF跟踪算法(实例代码)
2020/01/08 Python
Python列表去重复项的N种方法(实例代码)
2020/05/12 Python
没编程基础可以学python吗
2020/06/17 Python
北美最大的手工艺品零售商之一:Michaels Stores
2019/02/27 全球购物
俄罗斯最大的在线珠宝大卖场:Nebo
2019/12/08 全球购物
体育教师工作总结的自我评价
2013/10/10 职场文书
校园安全广播稿
2014/02/08 职场文书
农村文化活动总结
2014/08/28 职场文书
2014光棍节单身联谊活动策划书
2014/10/10 职场文书
浅谈Redis 中的过期删除策略和内存淘汰机制
2022/04/03 Redis