0

I'm trying to insert values into my db for the MyAccount table using placeholders. I think the issue lies in the fact that I have a field that is autoincrement and so I am not referencing it. I keep getting different errors, such as database data type mismatch which i think is for the autoincrement field that has no input for it (accountID) and it's just not working and I have tried to look up so many different variations. Any help?

db I tried this, I was expecting the values to insert into the db

2 Answers2

1

You'll need to call execute like (e.g.)

cur = con.cursor()
cur.execute(
    'INSERT INTO MyAccount (fullName, username, password, school, phoneNumber, yearGroup) VALUES (?, ?, ?, ?, ?, ?)',
    (input_fullName, input_username, input_password, input_school, input_phoneNumber, input_yearGroup),
)
con.commit()

, that is

  • the query as a string with ? placeholders (and I've here spelled out the column names so the placeholders' order doesn't matter)
  • the placeholders' values as a single tuple

This (and the alternative dictionary method) is documented in the sqlite3 module's documentation.

AKX
  • 152,115
  • 15
  • 115
  • 172
0

As AKX mentioned you have to pass the parameters by tuple or list. Here's a short example for a function:

def qry_exec(db, sql, parameters):
    qry = QSqlQuery (db)
    qry.prepare (sql)
    for value in parameters:
       qry.addBindValue (value)
    if not qry.exec_ ():
        print (qry.lastError ().text ())
        return False
    else:
        return True

You can call it by:

    sql = "INSERT INTO dbtable (field1, field2, field3) VALUES ( ?, ?, ?)"
    ret = QtSqlTools.qry_exec (db, sql, [ data1, data2, data3])

where db is an open database

Papageno
  • 305
  • 3
  • 15