python & sqlite – Bind parameters when multiple columns with same name are present

Question:

I have the following update query:

UPDATE table1 SET name = ?, surname = ?, birth_date = ?, sex = ? WHERE name = ? AND surname = ?

I’m running this query through the sqlite3 python package, and specifically using this method:

    def _connect_and_execute(query, data=None):
        conn = None
        try:
            conn = sqlite3.connect(DB_FILE_PATH)
            cur = conn.cursor()
            if data is None:
                cur.execute(query)
            else:
                cur.execute(query, data)
            conn.commit()
        except sqlite3.Error as e:
            logging.error(e)
            raise e
        finally:
            if conn:
                conn.close()

DB_FILE_PATH is a constant which holds the path to the sql file. The method is called by using the above query as query parameter and the list ["John", "Johnson", "01/01/2000", "M", "John", "Johnson"].

The query executes without errors, but without actually changing the values in the database (check through a database explorer software and with other select queries). Obviously the corresponding record to update already exists.

I did a little search on the internet and my hypothesis for this behaviour is that the name and surname columns are referenced twice for bind parameters. To my understanding, what this page states is that it is possible to bind values by using the corresponding indexes. I tried to update the query to:

UPDATE table1 SET name = ?1, surname = ?2, birth_date = ?3, sex = ?4 WHERE name = ?5 AND surname = ?6

but the behaviour is still the same.

Is it possible to bind parameters to the same columns twice? Is that the problem in my case? If so, which can be a possible solution?

Asked By: mattiatantardini

||

Answers:

I found where I was wrong. The problem was not in the update query, but in the values of the parameters that I passed to be bound. Indeed, they contain numbers, but I passed them as integers and not as strings. By casting them to string I solved the problem.

I also checked that both queries in the question are working properly, there’s no need to specify the parameter indexes even if the same column is referenced multiple times.

Answered By: mattiatantardini
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.