C#如何将布尔值插入数据库?

4

我在将布尔值插入数据库时遇到了问题。 我的结构很简单:

struct
{
   string name;
   bool isStudent;
}

我希望你能够将其插入到数据库中,就像这样:
 dbCommand.CommandText = "INSERT INTO People (name, isStudent) VALUES ('" + people1.name + "', " + people1.isStudent + ")";
 dbCommand.ExecuteNonQuery();

但是它抛出异常:

SQLite错误,没有这样的列:True


它告诉你在你的数据库中该字段不存在。你的数据库结构是什么?描述数据库表 - Luke
插入 @string@string = "标准SQL注入警告。" - Hogan
布尔值以 10 存储为 bit,你需要使用 ? : 来解决这个问题。 - Bastardo
3个回答

4

尝试使用:

dbCommand.CommandText = "INSERT INTO People (name, isStudent) VALUES ('" + people1.name + "', '" + people1.isStudent + "')";

请注意,'true''false'将以这种方式加引号。
或者:
int val = isStudent ? 1 : 0;
dbCommand.CommandText = "INSERT INTO People (name, isStudent) VALUES ('" + people1.name + "', " + val + ")";

1代表真值,0代表假值。


4

使用参数化查询,您就不必担心引号或值的格式(此外,这是一种良好的做法,可以避免 SQL 注入):

dbCommand.CommandText = "INSERT INTO People (name, isStudent) 
                         VALUES (@name, @isStudent)";
dbCommand.Parameters.AddWithValue("@name", people1.name);
dbCommand.Parameters.AddWithValue("@isStudent", people1.isStudent);
dbCommand.ExecuteNonQuery();

1

SQLite 没有布尔列类型,您正在构造自己的 SQL 语句。 如果您想这样做,则需要反复转换 1 和 0。

我也认为 .net 封装程序会替你完成这项工作。但是,您必须使用 SQL 参数而不是自己构建字符串,即使只是给它一个机会也要这样做。

构建参数化查询(?)还可以让 SQL lite 缓存已编译的语句。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接