0

I wrote def addmember to add member to database.db. I want no repeat in user name, example: when i add member (1,1) to database, i cannot add member (1,2) to my database because already have user with username "1". But my code still allow it ! Can some one help me ? Node that self.textEdit.toPlainText(), self.textEdit_2.toPlainText() is just my qtextedit object, dont mind it

def addmember(self):
        self.connection = sqlite3.connect("database.db")
        cur = self.connection.cursor()
        cur.execute("CREATE TABLE IF NOT EXISTS USERS(USERNAME TEXT ,PASSWORD TEXT)")
        cur.execute("SELECT * FROM USERS WHERE USERNAME=?", (self.textEdit.toPlainText()))
        for row in cur.fetchall():
            print(row)
        if (len(cur.fetchall())==0):

            cur.execute("INSERT INTO USERS VALUES(?,?)",(self.textEdit.toPlainText(), self.textEdit_2.toPlainText()))
            self.connection.commit()
            self.textEdit.clear()
            self.textEdit_2.clear()
            cur.close()
        else:
            self.textEdit.clear()
            self.textEdit_2.clear()
            cur.close()
        self.connection.commit()
        self.connection.close()
dauhuong68
  • 19
  • 1
  • 7

1 Answers1

0

Your calling fetchall twice. The first fetches all the rows. The second will never get any rows and the len will always be 0 so your insert will always happen.

James Cole
  • 24
  • 5
  • i deleted "for row in cur.fetchall(): print(row)" What if i want to allow (1, 2) to be create, only (1,1) are not allow to be add again ? I mean account with same username and different pass are allowed, but same account cant add again. I write cur.execute("SELECT * FROM USERS WHERE USERNAME=? AND PASSWORD=?", (self.textEdit.toPlainText(),self.textEdit_2.toPlainText())) but it not work – dauhuong68 Dec 16 '17 at 11:14
  • That looks right. You might enclose the ? in '?' . Also check this answer that Alex posted about parameter types. https://stackoverflow.com/a/902836/8652974 – James Cole Dec 16 '17 at 21:35