黑松山资源网 Design By www.paidiu.com
本文实例为大家分享了如何利用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数据库增删改查操作的相关操作,希望对大家的学习有所帮助。
黑松山资源网 Design By www.paidiu.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
黑松山资源网 Design By www.paidiu.com
暂无评论...
更新日志
2024年10月09日
2024年10月09日
- s14全球总决赛瑞士轮什么时候开始 s14瑞士轮开始时间介绍
- 晨报|《使命召唤21》全球发布预告 《异形:隔离》续作官宣开发中
- 隐形女联动毁灭博士?杰西卡·阿尔巴与小唐尼晒合影
- 《博德之门3》7号补丁发布后:Mod下载量达到2200万次!
- 徐璨宾《井底的蚯蚓》[FLAC/分轨][218.37MB]
- 王冰冰《Vaga Luna 月球漫游》[320K/MP3][62.76MB]
- 证声音乐图书馆《蔚蓝海岸·爵士度假日》[320K/MP3][59.79MB]
- 群星.1993-飞图合唱歌曲精丫飞图】【WAV+CUE】
- 王霏霏.2024-TOOOOO.BUSY(EP)【SNMUSIC】【FLAC分轨】
- 张宇.2016-好男人的情歌NEWXRCD【金牌大风】【WAV+CUE】
- 《食戟之灵》小林龙胆兔女郎比基尼版模型即将发售
- 重大里程碑!九号电动第500万台智能两轮电动车正式下线
- TGA主持人发文祝贺《暗喻幻想》 国外网友:提名稳了?
- 【原神】V5.0攻略 | 旋曜玉帛收集攻略(序号81~序号90)
- 【原神】V5.0攻略 | 旋曜玉帛收集攻略(序号91~序号100)