2017-08-08 108 views
1

如何判斷一個sqlite3的數據庫中存在的值,蟒蛇如何判斷一個sqlite3的數據庫中存在的值,蟒蛇

這是到目前爲止我的代碼:

def signup(): 
    email = request.form['email'] 
    username = request.form['user'] 
    password = request.form['password'] 
    g.db.execute("INSERT INTO users VALUES (?, ?, ?)", [email, username, password]) 
    g.db.commit() 

我想它只能將值插入到數據庫中,如果emailusername不在數據庫中,但我不知道從哪裏開始。

回答

3

您只需在插入前進行查詢,然後執行fetchone即可。如果fetchone回報的東西,那麼你肯定知道,有一個記錄已經在具有emailusername的DB:

def signup(): 
    email = request.form['email'] 
    username = request.form['user'] 
    password = request.form['password'] 

    # Create cursor object 
    cur = g.db.cursor() 

    # run a select query against the table to see if any record exists 
    # that has the email or username 
    cur.execute("""SELECT email 
          ,username 
        FROM users 
        WHERE email=? 
         OR username=?""", 
       (email, username)) 

    # Fetch one result from the query because it 
    # doesn't matter how many records are returned. 
    # If it returns just one result, then you know 
    # that a record already exists in the table. 
    # If no results are pulled from the query, then 
    # fetchone will return None. 
    result = cur.fetchone() 

    if result: 
     # Record already exists 
     # Do something that tells the user that email/user handle already exists 
    else: 
     cur.execute("INSERT INTO users VALUES (?, ?, ?)", (email, username, password)) 
     g.db.commit() 
+0

你不能這樣做在一個線,如:'g.db.execute (「INSERT INTO users VALUES(:email,:username,:password)WHERE users.email <>:email AND users.username <>:username」,{「email」:email,「username」:username,「password」 :密碼})'? – Adonis

+0

我不確定這是我問的。如果電子郵件位於電子郵件列中,或者用戶位於用戶名列中,我想轉到您放入代碼的其他位置。 – Daniel

+1

@Daniel然後我會修改爲:'選擇電子郵件,用戶名FROM users WHERE email =?或用戶名=?'。你指定了「'email'和'username'」,所以我假設你想進行兩次檢查。我會對我的答案進行更改。 –