Sqlite

使用 % 將多個值插入 SQL

  • February 24, 2020

這有效:

cursor = conn.execute("""Select FAMILY,F_NAME from birthday where B_MONTH = '%s' """ % (currentMonth))

我似乎無法使用 AND 子句將其擴展為還包括 day,我收到語法錯誤:

cursor = conn.execute("""Select FAMILY,F_NAME from birthday where B_MONTH = '%s' AND B_DAY = '%s' """ % (currentMonth),%(currentDay))

%運算符在其左側接受一個字元串,在其右側接受一個值列表:

execute("SELECT ... WHERE B_MONTH = '%s' AND B_DAY = '%s'" % (currentMonth, currentDay))

請注意 using%與字元串一起使用時會引入 SQL 注入的風險,因此您應該始終使用 SQL 參數來代替:

execute("SELECT ... WHERE B_MONTH = ? AND B_DAY = ?", (currentMonth, currentDay))

不要將目前月份/日期作為參數從 python 傳輸,SQLite 可以使用它自己的函式來完成。

cursor = conn.execute("""SELECT family,f_name 
                        FROM birthday 
                        WHERE b_month = STRFTIME('%m','now') 
                          AND b_day = STRFTIME('%d','now')""")

引用自:https://dba.stackexchange.com/questions/260409