【问题标题】:Storing Data in SQLite在 SQLite 中存储数据
【发布时间】:2017-04-16 17:09:21
【问题描述】:

有没有办法在 SQLite 数据库中存储 TEXT 而 SQLite 不尝试解析它? 遇到一个问题,当您存储类似于 SQLite 查询的 TEXT 时,它会出于某种原因尝试对其进行解析。

我用来保存 TEXT 的查询:"insert into tableName (Name, DateCreated, Reminder, Content) values ('name', 'currentDate', 'reminder', 'content')".

我正在尝试保存的类似文本:"SELECT NAME FROM sqlite_master WHERE TYPE='table' ORDER BY NAME".

当我尝试保存类似的内容时,它显示:错误:SQL 逻辑错误或“表”附近缺少数据库:语法错误

请注意,值(名称、currentDate、提醒、内容)不是硬编码的,它们是作为字符串传递的。实际代码如下:

SQLiteCommand command = new SQLiteCommand("insert into " + cateName + " (Name, DateCreated, Reminder, Content) values ('" + noteName + "', '" + currentDate + "', '" + reminder + "', '" + content + "')", connection);

感谢您的任何意见。

【问题讨论】:

  • 请显示您用于保存值的代码。您目前的 INSERT 语句被硬编码为字符文字......我确定这不是您实际在做的事情。 (我怀疑问题是您应该使用参数化 SQL,但如果不查看您的代码,我们就无法判断。)
  • 你在第二个文本中有一个额外的“,这是准备这个问题时的错字吗?
  • @JonSkeet,抱歉,刚刚更新了代码。
  • @waTeim,抱歉打错了。
  • 听起来您正面临自我诱导的 SQL 注入攻击 :-)

标签: c# sqlite


【解决方案1】:

我怀疑,问题在于您将值直接放入 SQL 中 - 甚至没有尝试转义它们。 不要那样做。 除了您遇到的问题,您还向SQL injection attack 敞开心扉。请改用参数化 SQL,并为参数指定值。

例如:

// It's not clear what cateName is, but I'll assume *that* bit is valid...
string sql = new SQLiteCommand("insert into " + cateName +
     " (Name, DateCreated, Reminder, Content) values " +
     "(@Name, @DateCreated, @Reminder, @Content)");

using (var command = new SQLiteCommand(sql, connection))
{
    command.Parameters.Add("@Name", SQLiteType.Text).Value = noteName;
    command.Parameters.Add("@DateCreated", SQLiteType.DateTime).Value = currentDate;
    command.Parameters.Add("@Reminder", SQLiteType.Text).Value = reminder;
    command.Parameters.Add("@Content", SQLiteType.Text).Value = content;
    command.ExecuteNonQuery();
}

【讨论】:

  • 感谢您的回复,cateName 是tableName 变量,感谢您的解释,但是command.Parameters.Add 不接受SQLiteType,只接受不包含TEXT 或DateTime 的DbType。
  • 通过使用 DbType.String 可以很好地保存内容。我应该使用相同的(参数化)方法从数据库中检索数据吗?非常感谢您的帮助。
  • @NetInfo:是的,您应该为 all 动态值使用参数化 SQL。它以各种方式提供帮助。
  • 非常感谢。非常感谢你的帮助。
猜你喜欢
  • 2020-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-12
  • 2018-11-27
相关资源
最近更新 更多