current position:Home>Check whether the data obtained by post already exists in the database

Check whether the data obtained by post already exists in the database

2022-02-03 01:30:27 CSDN Q & A

POST If the obtained data already exists in the database Genre table , Should be displayed “ The data already exists in the database ”, But there's something wrong with the code , Only direct display “ Failed to add the specified content to the database ”

@app.route('/add/genre', methods = ['POST'])def add_genre():    if request.method == 'POST':        genre = request.form['genre']    conn = sqlite3.connect("Mydatabase.db")    cur = conn.cursor()    cur.execute("SELECT Name FROM Genre")    genreName = cur.fetchall()    string = " Successful addition  " + genre + "  To the database ."    prompt = {string}    error = ""    if genre in genreName:     // ←        prompt = {
   
   
   
   " The data already exists in the database "}        error = "exist"    else:        with sqlite3.connect("Mydatabase.db") as conn:            try:                cur = conn.cursor()                cur.execute("INSERT INTO Genre (Name) VALUES (?)", ('genre'))                conn.commit()            except:                prompt = {
   
   
   
   " Failed to add the specified content to the database "}                error = "exist"        return render_template('add_genre.html', messages=prompt, error=error)



Refer to the answer 1:

Make suggestions
1、 If the amount of data is very large , In this way, you can directly read the whole library , Memory resources are used too much .
2、 It is suggested to change to this logic ( According to your code , Probably adjusted , It hasn't been verified )

@app.route('/add/genre', methods=['POST'])def add_genre():    prompt = {
   
   
   
   " No data "}    error = "error"    if request.method == 'POST':        genre = request.form['genre']        conn = sqlite3.connect("Mydatabase.db")        cur = conn.cursor()        cur.execute("SELECT Name FROM Genre where name = '{}'".format(genre))        genreName = cur.fetchall()        if len(genreName)>0:            prompt = {
   
   
   
   " The data already exists in the database "}            error = "exist"        else:            try:                cur = conn.cursor()                cur.execute("INSERT INTO Genre (Name) VALUES (?)", ('genre'))                conn.commit()            except:                prompt = {
   
   
   
   " Failed to add the specified content to the database "}                error = "exist"                        string = " Successful addition  " + genre + "  To the database ."            prompt = {
   
   
   
   string}            error = ""        return render_template('add_genre.html', messages=prompt, error=error)



Refer to the answer 2:

copyright notice
author[CSDN Q & A],Please bring the original link to reprint, thank you.
https://en.primo.wiki/2022/02/202202030130249316.html

Random recommended