【问题标题】:How can I use an integer like a string in a SQL statement如何在 SQL 语句中使用像字符串一样的整数
【发布时间】:2014-12-17 04:43:37
【问题描述】:

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

我想在 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 值只是一个数字,记录不会被删除。

很遗憾,该字段的值可以是数值或文本值。

非常欢迎任何帮助!

【问题讨论】:

  • 感谢您编辑帖子。下次我会注意你的更正

标签: objective-c sqlite nsstring


【解决方案1】:

您在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 注入攻击。

【讨论】:

  • txtMostrado 并不总是数值,它可以是数值或文本字符串。
  • @xur 很好,那么sqlite3_bind_text 是您的朋友(但可能与您当前的问题无关)。接下来要检查的是txtaborrar 的准确内容与数据库中的实际内容。告诉我们两者都是什么。令人讨厌的是,在处理字符串时,是否存在空格或小数点会产生很大的不同。不幸的是,这里不足以诊断问题的根源。如果我们要进一步帮助您,您需要记录这些值并相应地更新您的问题。
猜你喜欢
  • 2013-10-29
  • 2011-11-07
  • 2018-10-11
  • 2021-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多