当前位置:Gxlcms > Python > Python的Sql数据库增删改查操作简单封装方法

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

时间:2021-07-01 10:21:17 帮助过:71人阅读

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

1.insert

  1. import mysql.connector
  2. import os
  3. import codecs
  4. #设置数据库用户名和密码
  5. user='root';#用户名
  6. pwd='root';#密码
  7. host='localhost';#ip地址
  8. db='mysql';#所要操作数据库名字
  9. charset='UTF-8'
  10. cnx = mysql.connector.connect(user=user,password=pwd, host=host, database=db)
  11. #设置游标
  12. cursor = cnx.cursor(dictionary=True)
  13. #插入数据
  14. #print(insert('gelixi_help_type',{'type_name':'\'sddfdsfs\'','type_sort':'283'}))
  15. def insert(table_name,insert_dict):
  16. param='';
  17. value='';
  18. if(isinstance(insert_dict,dict)):
  19. for key in insert_dict.keys():
  20. param=param+key+","
  21. value=value+insert_dict[key]+','
  22. param=param[:-1]
  23. value=value[:-1]
  24. sql="insert into %s (%s) values(%s)"%(table_name,param,value)
  25. cursor.execute(sql)
  26. id=cursor.lastrowid
  27. cnx.commit()
  28. return id

2.delete

  1. def delete(table_name,where=''):
  2. if(where!=''):
  3. str='where'
  4. for key_value in where.keys():
  5. value=where[key_value]
  6. str=str+' '+key_value+'='+value+' '+'and'
  7. where=str[:-3]
  8. sql="delete from %s %s"%(table_name,where)
  9. cursor.execute(sql)
  10. cnx.commit()

3.select

  1. #取得数据库信息
  2. # print(select({'table':'gelixi_help_type','where':{'help_show': '1'}},'type_name,type_id'))
  3. def select(param,fields='*'):
  4. table=param['table']
  5. if('where' in param):
  6. thewhere=param['where']
  7. if(isinstance (thewhere,dict)):
  8. keys=thewhere.keys()
  9. str='where';
  10. for key_value in keys:
  11. value=thewhere[key_value]
  12. str=str+' '+key_value+'='+value+' '+'and'
  13. where=str[:-3]
  14. else:
  15. where=''
  16. sql="select %s from %s %s"%(fields,table,where)
  17. cursor.execute(sql)
  18. result=cursor.fetchall()
  19. return result

4.showtable,showcolumns

  1. #显示建表语句
  2. #table string 表名
  3. #return string 建表语句
  4. def showCreateTable(table):
  5. sql='show create table %s'%(table)
  6. cursor.execute(sql)
  7. result=cursor.fetchall()[0]
  8. return result['Create Table']
  9. #print(showCreateTable('gelixi_admin'))
  10. #显示表结构语句
  11. def showColumns(table):
  12. sql='show columns from %s '%(table)
  13. print(sql)
  14. cursor.execute(sql)
  15. result=cursor.fetchall()
  16. dict1={}
  17. for info in result:
  18. dict1[info['Field']]=info
  19. return dict1

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

更多Python的Sql数据库增删改查操作简单封装方法相关文章请关注PHP中文网!

人气教程排行