如何在SQL语句中使用类似字符串的整数

时间:2014-10-21 20:16:09

标签: objective-c sqlite nsstring

编辑,试图更好地解释上下文。

我想在Xcode中删除SQLite DB上的记录。

记录的值添加如下:

sql = [NSString stringWithFormat:@"INSERT INTO tblTextos (\"txtMostrado\", \"txtCopiado\") VALUES(\"%@\", \"%@\")", [txt2BS stringValue], [txt2BC stringValue]];// Where txt2BS and txt2BC are  NSTextField     

要删除记录,我正在使用下一句话:

sentenciaSQL = [NSString stringWithFormat:@"DELETE FROM tblTextos WHERE txtMostrado = '%@'", txtaborrar];  //where tblTextos  is a table, txtMostrado a field (text field) and txtaborrar a String variable (NSString).

问题是txtaborrar变量里面只有一个数字,例如22.然后句子不起作用,记录也不会被删除。 我尝试使用以下内容将变量值强制为字符串:

txtaborrar = [NSString stringWithFormat: @"%@",[comboTodos stringValue]];//where Combotodos is a combo

但它不起作用。如果txtaborrar值只是一个数字,则不会删除该记录。

不幸的是,该字段的值可以是数值或文本值。

非常欢迎任何帮助!

1 个答案:

答案 0 :(得分:2)

您在txtMostrado列中保留了哪些数据?它总是数值吗?如果是这样,你根本不应该将它们存储为数字的文本表示。实际上将它们存储为数值。

此外,您不应该使用stringWithFormat构建SQL语句。您应该使用?占位符。因此,您的SQL将是:

sentenciaSQL = @"DELETE FROM tblTextos WHERE txtMostrado = ?"; //where tblTextos is a table, txtMostrado a field and txtaborrar a String variable (NSString).

然后,在使用sqlite3_prepare_v2准备SQL语句之后,但在调用sqlite3_step之前,您需要将值绑定到SQL中的每个?占位符。如果此txtMostrado实际上是整数数据类型,您可以执行以下操作:

sqlite3_bind_int(statement, 1, value);  // where `1` is the 1-based index of the occurrence of the ? in the SQL; and `value` is the int variable holding the value

如果txtMostrado是字符串数据类型,您可以执行以下操作:

sqlite3_bind_text(statement, 1, [value UTF8String], -1, NULL);  // where `1` is the 1-based index of the occurrence of the ? in the SQL; and `value` is the NSString variable holding the value

有关详细信息,请参阅sqlite3_bind_xxx() documentation

此规则适用于插入值以及提供where子句时,如上所述。

注意,这完全消除了在SQL中使用引号(即使使用sqlite_bind_text)并解决了当字符串值本身包含引号时可能出现的问题。它还可以保护您免受SQL注入攻击。