python数据库操作封装_利用Python对数据库的增删改查进行简单的封装

封装sql,我用的版本是Python3

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值