欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python Sql數(shù)據(jù)庫增刪改查操作簡單封裝

 更新時(shí)間:2016年04月18日 14:35:05   作者:mrmusic  
這篇文章主要為大家介紹了Python Sql數(shù)據(jù)庫增刪改查操作簡單封裝,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了如何利用Python對數(shù)據(jù)庫的增刪改查進(jìn)行簡單的封裝,供大家參考,具體內(nèi)容如下

1.insert    

import mysql.connector
import os
import codecs
#設(shè)置數(shù)據(jù)庫用戶名和密碼
user='root';#用戶名
pwd='root';#密碼
host='localhost';#ip地址
db='mysql';#所要操作數(shù)據(jù)庫名字
charset='UTF-8'
cnx = mysql.connector.connect(user=user,password=pwd, host=host, database=db)
#設(shè)置游標(biāo)
cursor = cnx.cursor(dictionary=True)
#插入數(shù)據(jù)
#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    

#取得數(shù)據(jù)庫信息
# 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'))
#顯示表結(jié)構(gòu)語句
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數(shù)據(jù)庫增刪改查操作的相關(guān)操作,希望對大家的學(xué)習(xí)有所幫助。

相關(guān)文章

最新評論