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

yipeiwu_com5年前Python基础

本文实例为大家分享了如何利用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之信息加密题目详解

1.贴题 题目来自PythonTip 信息加密 给你个小写英文字符串a和一个非负数b(0<=b<26), 将a中的每个小写字符替换成字母表中比它大b的字母。这里将字母表...

python中scikit-learn机器代码实例

我们给大家带来了关于学习python中scikit-learn机器代码的相关具体实例,以下就是全部代码内容: # -*- coding: utf-8 -*- import num...

用pytorch的nn.Module构造简单全链接层实例

python版本3.7,用的是虚拟环境安装的pytorch,这样随便折腾,不怕影响其他的python框架 1、先定义一个类Linear,继承nn.Module import tor...

Python实现使用卷积提取图片轮廓功能示例

Python实现使用卷积提取图片轮廓功能示例

本文实例讲述了Python实现使用卷积提取图片轮廓功能。分享给大家供大家参考,具体如下: 一、实例描述 将彩色的图片生成带边缘化信息的图片。 本例中先载入一个图片,然后使用一个“3通道输...

python的三目运算符和not in运算符使用示例

python的三目运算符和not in运算符使用示例

三目运算符也就是三元运算符 一些语言(如Java)的三元表达式形如: 判定条件?为真时的结果:为假时的结果 result=x if x Python的三元表达式有如下几种书写方法...