mysql.connector操作垃圾分类数据

mysql.connector操作垃圾分类数据_第1张图片

表格数据转csv格式导入
mysql.connector操作垃圾分类数据_第2张图片
mysql.connector操作垃圾分类数据_第3张图片

import mysql.connector

#连接数据库
def dbConnect(db_host):
    db_user = 'root'
    db_pass = '12345%$#@!'
    db_name = 'pythondb'
    db_conn = mysql.connector.connect(user=db_user,password=db_pass,host=db_host,database=db_name)
    return db_conn

#获取数据
def sqlOpt(rubbish_name):
    db_conn = dbConnect('localhost')
    sql = "select * from pythondb.rubbishes where Name = '{}'".format(rubbish_name)
    try:
        cursor = db_conn.cursor()
        cursor.execute(sql)
        result=cursor.fetchall()
        index={1:'可回收物',2:'有害垃圾',4:'厨余垃圾',8:'其他垃圾'}
        return(str(index.get(result[0][1],'大件垃圾')))
    except:
        return('未知垃圾')
    finally:
        db_conn.close()
        
#增添/修改数据
def sqlInsert(rubbish_name,class_name):
    db_conn = dbConnect('localhost')
    index={'可回收物':1,'有害垃圾':2,'厨余垃圾':4,'其他垃圾':8}
    val = (rubbish_name,index[class_name])
    sql = "INSERT ignore INTO rubbishes (name,class) values {}".format(val)
    try:
        cursor = db_conn.cursor()
        cursor.execute(sql)
        db_conn.commit()
        return True
    except:
        return False
    finally:
        db_conn.close()

#删除数据
def sqlDel(rubbish_name):
    db_conn = dbConnect('localhost')
    na = (rubbish_name,)
    sql = "DELETE FROM pythondb.rubbishes WHERE Name = %s"
    try:
        cursor = db_conn.cursor()
        cursor.execute(sql,na)
        db_conn.commit()
        return True
    except:
        return False
    finally:
        db_conn.close()

mysql.connector操作垃圾分类数据_第4张图片
mysql.connector操作垃圾分类数据_第5张图片

你可能感兴趣的:(mysql,SRDP)