在 'CREATE TABLE' 语句中绑定默认值是否很常见?
Is it common to bind default values in 'CREATE TABLE' statements?
要不要直接执行(伪代码)...
q = "CREATE TABLE `usermood` { `id` INT, `name` TEXT, `mood` VARCHAR DEFAULT 'gloomy' }";
exec(q);
...或绑定到(未)命名的占位符?
q = "CREATE TABLE `usermood` { `id` INT, `name` TEXT, `mood` VARCHAR DEFAULT :mood }";
prepare(q);
bind(q, ":mood", 'gloomy');
exec(q);
我从未在任何示例代码中看到它。
它不是关于转义的安全性(因为我控制创建语句),而是关于将值转换为数据库兼容的格式(按类型自动选择内容表示)。
我正在使用 MySQL 以及 SQLite3。
是否有不支持在创建语句中绑定的数据库驱动程序?
如果有人感兴趣:我正在使用 QSqlQuery
和 QVariant
作为值。
您将在以下情况下使用参数绑定:
您正在使用来自未知来源的值,并且您想防止 SQL 注入。
您想准备一个语句并使用不同的参数值重复执行它。
对于您的 CREATE TABLE 示例,这些都不太可能。
我从未在任何 DDL 语句中使用过参数。
P.S.: 你不能为 TEXT 列设置 DEFAULT,不管它是 DDL 语句中的绑定参数还是文字值,但我猜你上面的例子是人为的。
SQLite 明确禁止绑定默认值:
An explicit DEFAULT clause may specify that the default value is NULL, a string constant, a blob constant, a signed-number, or any constant expression enclosed in parentheses. A default value may also be one of the special case-independent keywords CURRENT_TIME, CURRENT_DATE or CURRENT_TIMESTAMP. For the purposes of the DEFAULT clause, an expression is considered constant if it does contains no sub-queries, column or table references, bound parameters, or string literals enclosed in double-quotes instead of single-quotes.
(我强调的)
要不要直接执行(伪代码)...
q = "CREATE TABLE `usermood` { `id` INT, `name` TEXT, `mood` VARCHAR DEFAULT 'gloomy' }";
exec(q);
...或绑定到(未)命名的占位符?
q = "CREATE TABLE `usermood` { `id` INT, `name` TEXT, `mood` VARCHAR DEFAULT :mood }";
prepare(q);
bind(q, ":mood", 'gloomy');
exec(q);
我从未在任何示例代码中看到它。
它不是关于转义的安全性(因为我控制创建语句),而是关于将值转换为数据库兼容的格式(按类型自动选择内容表示)。
我正在使用 MySQL 以及 SQLite3。
是否有不支持在创建语句中绑定的数据库驱动程序?
如果有人感兴趣:我正在使用 QSqlQuery
和 QVariant
作为值。
您将在以下情况下使用参数绑定:
您正在使用来自未知来源的值,并且您想防止 SQL 注入。
您想准备一个语句并使用不同的参数值重复执行它。
对于您的 CREATE TABLE 示例,这些都不太可能。
我从未在任何 DDL 语句中使用过参数。
P.S.: 你不能为 TEXT 列设置 DEFAULT,不管它是 DDL 语句中的绑定参数还是文字值,但我猜你上面的例子是人为的。
SQLite 明确禁止绑定默认值:
An explicit DEFAULT clause may specify that the default value is NULL, a string constant, a blob constant, a signed-number, or any constant expression enclosed in parentheses. A default value may also be one of the special case-independent keywords CURRENT_TIME, CURRENT_DATE or CURRENT_TIMESTAMP. For the purposes of the DEFAULT clause, an expression is considered constant if it does contains no sub-queries, column or table references, bound parameters, or string literals enclosed in double-quotes instead of single-quotes.
(我强调的)