Python Sql数据库增删改查操作简单封装
本文实例为大家分享了如何利用Python对数据库的增删改查进行简单的封装,供大家参考,具体内容如下
1.insert
importmysql.connector importos importcodecs #设置数据库用户名和密码 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'})) definsert(table_name,insert_dict): param=''; value=''; if(isinstance(insert_dict,dict)): forkeyininsert_dict.keys(): param=param+key+"," value=value+insert_dict[key]+',' param=param[:-1] value=value[:-1] sql="insertinto%s(%s)values(%s)"%(table_name,param,value) cursor.execute(sql) id=cursor.lastrowid cnx.commit() returnid
2.delete
defdelete(table_name,where=''): if(where!=''): str='where' forkey_valueinwhere.keys(): value=where[key_value] str=str+''+key_value+'='+value+''+'and' where=str[:-3] sql="deletefrom%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')) defselect(param,fields='*'): table=param['table'] if('where'inparam): thewhere=param['where'] if(isinstance(thewhere,dict)): keys=thewhere.keys() str='where'; forkey_valueinkeys: value=thewhere[key_value] str=str+''+key_value+'='+value+''+'and' where=str[:-3] else: where='' sql="select%sfrom%s%s"%(fields,table,where) cursor.execute(sql) result=cursor.fetchall() returnresult
4.showtable,showcolumns
#显示建表语句 #tablestring表名 #returnstring建表语句 defshowCreateTable(table): sql='showcreatetable%s'%(table) cursor.execute(sql) result=cursor.fetchall()[0] returnresult['CreateTable'] #print(showCreateTable('gelixi_admin')) #显示表结构语句 defshowColumns(table): sql='showcolumnsfrom%s'%(table) print(sql) cursor.execute(sql) result=cursor.fetchall() dict1={} forinfoinresult: dict1[info['Field']]=info returndict1
以上就是PythonSql数据库增删改查操作的相关操作,希望对大家的学习有所帮助。