2014-05-05 33 views
0

我使用的是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無線thout重複:比這裏使用循環和調用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> 

回答

0

不是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周的ClientLogin =卡勒

ID = 2的ClientLogin =鴨

編輯: 對於獨特之處創建表格時,多列執行此操作:

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

最後一件事是可以隨你想要發生的任何事情取代。

相關問題