S
S
szjyakgf2022-03-23 14:54:46
Python
szjyakgf, 2022-03-23 14:54:46

How to pass value to sqlite3 command?

I have a users table, for example, I need to find out how many 1 are in column n6 (column with numbers 1,2,3):

cur.execute("SELECT COUNT(*) FROM users WHERE n6 == 1")
xxx = cur.fetchone()
print(xxx)#получаю вывод: (5,)

Everything works, but I need to look for 1 not only in n6, there are also other columns n7, n8, n9... To do this, I need to substitute the name of the column, but it does not work:
mmml = 'n' + str(6)
cur.execute("SELECT COUNT(*) FROM users WHERE ? == 1", (mmml, ))
xxx = cur.fetchone()
print(xxx)#получаю вывод: (0,)

What could be the problem? When substituting n6, the output is always (0,) no difference to the data from the table

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
o5a, 2022-03-23
@szjyakgf

Value substitution in this form does NOT work for identifiers, which are table and field names. In this case, you can substitute through the usual string formatting:

cur.execute("SELECT COUNT(*) FROM users WHERE {} == 1".format(mmml))
или
cur.execute(f"SELECT COUNT(*) FROM users WHERE {mmml} == 1")

Perhaps it would be more correct to change the tables themselves, because these numbered n1...6 look like some kind of crutches.

A
Alexander, 2022-03-23
@shabelski89

eye bleeding :)

cur.execute("SELECT COUNT(*) FROM users WHERE ? = 1 OR ? = 1 ", ("n7","n8" ))
xxx = cur.fetchall()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question