国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python Sql數據庫增刪改查操作簡單封裝

2019-11-25 16:50:19
字體:
來源:轉載
供稿:網友

本文實例為大家分享了如何利用Python對數據庫的增刪改查進行簡單的封裝,供大家參考,具體內容如下

1.insert    

import mysql.connectorimport osimport 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數據庫增刪改查操作的相關操作,希望對大家的學習有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 铜鼓县| 饶平县| 固阳县| 清镇市| 晋州市| 象山县| 禄丰县| 宁波市| 翼城县| 罗平县| 兰溪市| 措美县| 西峡县| 苍南县| 临桂县| 昌平区| 冷水江市| 郎溪县| 怀集县| 临江市| 远安县| 资中县| 克拉玛依市| 额尔古纳市| 尉氏县| 沁阳市| 辽阳县| 彰武县| 利津县| 绥中县| 永川市| 北流市| 肥西县| 馆陶县| 荣成市| 蓬安县| 深水埗区| 印江| 宁阳县| 伊金霍洛旗| 楚雄市|