Flask 插入数据库时避免重复

0 投票
1 回答
670 浏览
提问于 2025-04-18 05:29

我正在使用Flaskr这个例子,想要在网页上显示数据库的内容,而且不想要重复的记录。为此,我修改了show_entries.html,变成了这样:

 {% extends "layout.html" %}
 {% block body %}
   {% if session.logged_in %}
     <form action="{{ url_for('add-entry') }}" method=post class=add-entry>
       <dl>
        <dt>Available:
        <dd><input type=text size=25 name=attribute1>
        <dt>Used:
        <dd><input type=text size=25 name=attribute2>
        <dd><input type=submit value=Update>
       </dl>
     </form>
   {% endif %}
     <table border="1" style="width:300px">
       <ul class=myDB>
       <tr>
         <th>Available</th>
         <td>{% for entry in myDB %} {{ entry.attribute1 }} {% endfor %}</td>
       </tr>
       <tr>
         <th>Used</th>
         <td>{% for entry in myDB %} {{ entry.attribute2 }} {% endfor %}</td>                  
       </tr>
       </ul>            
     </table>
 {% endblock %}

而我的myDB.py文件看起来是这样的:

.
.
.
@app.route('/')
def showEntries():
    db = get_db()
    cur = db.execute('select distinct attribute1, attribute2 from myDB order by id desc')
    myDB = cur.fetchall()
    return render_template('show_entries.html', myDB=myDB)

@app.route('/add', methods=['POST'])
def add-entry():
    if not session.get('logged_in'):
        abort(401)
    db = get_db()
    db.execute('insert or replace into myDB (attribute1, attribute2) values (?, ?)',
             [request.form['attribute1'], request.form['attribute2']])                   
    db.commit()
    flash('Database Updated')
    return redirect(url_for('showEntries'))
.
.
.

我想问的是,每次我更新数据库并刷新网页服务器时,还是会看到重复的记录。有没有什么办法可以显示attribute1和attribute2的更新值,而且不出现重复的记录呢?也就是说,除了在这里使用for循环来调用myDB里的所有条目之外,还有其他方法吗?

<td>{% for entry in myDB %} {{ entry.attribute1 }} {% endfor %}</td>

<td>{% for entry in myDB %} {{ entry.attribute2 }} {% endfor %}</td>

因为这样是行不通的

<td> {{ myDB.attribute1 }} </td>

<td> {{ myDB.attribute2 }} </td>

1 个回答

0

我不太确定这是不是你想问的,但我还是来回答一下。

在你创建数据库的时候,可以选择是否允许重复的变量或插入数据。

举个例子:

"create table registratedClients (id INTEGER PRIMARY KEY, clientLogin TEXT unique)"

这段代码只允许插入唯一的 clientLogin。 如果我使用这段代码:

"insert into registratedClients values (null," + "\'" + "Kalle" + "\')"
"insert into registratedClients values (null," + "\'" + "Duck" + "\')"
"insert into registratedClients values (null," + "\'" + "Kalle" + "\')"

我的数据库里只会包含:

id = 1 clientLogin = Kalle

id = 2 clientLogin = Duck

补充一下:如果想要在多个列中保持唯一性,可以在创建表的时候这样做:

 "create table registratedClients (id INTEGER PRIMARY KEY, clientLogin TEXT, chatName TEXT, UNIQUE(clientLogin, chatName) ON CONFLICT REPLACE)"

最后一部分可以替换成你想要的任何操作。

撰写回答