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内建模块struct实例详解

本文研究的主要是Python内建模块struct的相关内容,具体如下。 Python中变量的类型只有列表、元祖、字典、集合等高级抽象类型,并没有像c中定义了位、字节、整型等底层初级类型。...

在python中使用requests 模拟浏览器发送请求数据的方法

如下所示: import requests url='http://####' proxy={'http':'http://####:80'} headers={ "Accep...

python 中文件输入输出及os模块对文件系统的操作方法

整理了一下python 中文件的输入输出及主要介绍一些os模块中对文件系统的操作。 文件输入输出 1、内建函数open(file_name,文件打开模式,通用换行符支持),打开文件返回文...

Django学习笔记之Class-Based-View

前言 大家都知道其实学习Django非常简单,几乎不用花什么精力就可以入门了。配置一个url,分给一个函数处理它,返回response,几乎都没有什么很难理解的地方。 写多了,有些问题才...

python+pygame简单画板实现代码实例

python+pygame简单画板实现代码实例

疑问:pygame已经过时了吗? 过没过时不知道,反正这玩意官方已经快四年没有更新了。用的人还是蛮多的(相对于其他同类项目),不过大家都是用来写写小东西玩一玩,没有人用这个做商业项目。p...