简体   繁体   中英

How do I use the values in the tuple miltiple times when doing an execute in sqlite3

I'm trying to use the execute function of sqlite3 to sanitize the string that I got. However, I can't do it in my case because I can't figure out how to use the values in the tuple more than one time.

What I can do is this,

cursor.execute("""
                    select *
                    from rides r
                    where r.cno = c.cno
                    and (r.src like '%{0}%'
                    or r.dst like '%{0}%'
                    or e.lcode like '%{0}%'
                    and (r.src like '%{1}%'
                    or l3.address like '%{1}%')
                    and (r.src like '%{2}%'
                    or l1.address like '%{2}%')
                    ;
                    """.format(keywords[0], keywords[1], keywords[2]))

However, I learnt that it is open for sqlinjection attacks since the input is being directly used in here. Is there a way I could still use tuples at the end of the execute function multiple times?

sqlite3 puts their sanitation front-and-center in the docs. Use the named placeholder style.

https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.execute

# This is the qmark style:
cur.execute("insert into people values (?, ?)", (who, age))

# And this is the named style:
cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})

This answer to a previous post could help you visualize the fix as well: https://stackoverflow.com/a/12184247/10553976

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM