簡體   English   中英

無需復制即可將燒瓶插入數據庫

[英]Flask insert into database without duplicating

我正在使用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'))
.
.
.

我的問題是,每當我更新數據庫並刷新Web服務器時,我仍然看到重復項:因此,有什么方法可以顯示沒有重復項的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>

不能100%確定這是您要的內容,但是無論如何,這是我的答案。

創建數據庫時,可以選擇是否要允許重復的變量/插入。

例如:

"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個客戶端登錄= Kalle

id = 2 clientLogin =鴨子

編輯:對於多列中的唯一列,請在創建表時執行此操作:

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

最后一件事是可以替換為任何您想發生的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM