0

我正在尝试更新表中的任意列:

cursor.execute('update table set :n = :v where submitter = :s', 
               {'n':'col1', 'v': 10, 's': 'mike'})

但它给了我sqlite3.OperationalError: near ":n": syntax error。奇怪的是,当我这样做时它工作正常

cursor.execute('update table set col1 = :v where submitter = :s', 
               {'n':'col1', 'v': 10, 's': 'mike'})

为什么我似乎不能以节省注入的方式命名列?还有其他方法可以设置任意列吗?

4

2 回答 2

4

Only values can be bound; identifiers (e.g. column/table names) and other structural syntax cannot be bound with placeholders.

In general a prepared statement must have a "known query shape" and allowing dynamic identifiers would prohibit that. (There may be databases and database adapters that don't hold to this, but I have yet to meet one.)

于 2012-07-15T18:23:18.103 回答
2

Placeholders cannot, as you have discovered, be used as table or column names. Instead, you have to concatenate in a string for the dynamic table or column name.

It is therefore recommended to check it against a whitelist of available column names to be sure it is safe:

# Array of valid values for colname
valid_colnames = ['col1','col2','col3']
# Only do it if you received a safe known value
if colname in valid_colnames:
  cursor.execute('update table set ' + colname + ' = :v where submitter = :s', 
               {'v': 10, 's': 'mike'})
于 2012-07-15T18:24:19.230 回答