iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python Sql数据库增删改查操作简单封装
  • 151
分享到

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

操作简单数据库 2022-06-04 19:06:09 151人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

本文实例为大家分享了如何利用python对数据库的增删改查进行简单的封装,供大家参考,具体内容如下 1.insert import Mysql.connector import os imp

本文实例为大家分享了如何利用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数据库增删改查操作的相关操作,希望对大家的学习有所帮助。

--结束END--

本文标题: Python Sql数据库增删改查操作简单封装

本文链接: https://www.lsjlt.com/news/15008.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作