【问题标题】:How to stop sqlitedatareader from returning 0 if data is null?如果数据为空,如何阻止 sqlitedatareader 返回 0?
【发布时间】:2017-03-07 06:25:13
【问题描述】:

我正在尝试使用以下代码从 SQLite 数据库中的表中获取 1 列的数据。

System.Data.SQLite.SQLiteConnection m_dbConnection = new System.Data.SQLite.SQLiteConnection(String.Format("Data Source={0};Version=3;", filePath));
m_dbConnection.Open();    
using (SQLiteCommand cmd = new SQLiteCommand())
{ 
// Select query here
}
var command = new SQLiteCommand(Query, m_dbConnection);
SQLiteDataReader reader = command.ExecuteReader();
List<object> data = new List<object>();
while (reader.Read())
{
    if (reader[0].GetType() == typeof(DBNull)) // Always gives False
       data.Add(reader.GetString(0));
    else
       data.Add(reader.GetValue(0));
}

但是DBNull check 总是返回false,即使DataBase 中有null。因此,这里调用了reader.GetValue(0),并将DBNull 转换为0

注意:要获取的列的数据类型是int

我不希望这个 DBNull 被转换为 0。如果我这样做,那么我的任务就完成了。

while (reader.Read())
{
  try
  {
     data.Add(reader.GetString(0));
  }
  catch (Exception)
  {
     data.Add(reader.GetValue(0));                           
  }                                                                  
}

但这是错误的方式,因为在大多数情况下都会抛出异常,只有当数据为DBNull时才会发生异常。

请提出完成任务的方法。

【问题讨论】:

    标签: c# sqlite datareader


    【解决方案1】:

    对 REAL DbNull 值的正确检查是:

    string value;
    if (dataReader.IsDBNull(0)) value = "";
    else value = dataReader.GetString(0);
    

    如果你有字符串“null”

    string value = dataReader.GetString(0);
    if(value.ToLower()=="null")value="";
    

    【讨论】:

    • 不工作!!即使在这里 `if(reader.IsDBNull(0))' 总是返回 false。如果值为 null,则不会返回 true。
    • 哇哇。你确定有 REAL DbNull 吗?还是只有字符串'null'?因为这段代码非常适合 DbNull 的
    • 我确定它不是字符串,因为当我像 String str = reader[0] as String 一样传递它时,str 返回我 null
    • 错误答案。设置断点,看看里面到底有什么价值!没有必要有 null,as 如果有 int 值或字节,则可以返回 null。换句话说 - 确保 0string 列,它可能是数据库中的 null
    • 我在问题中也提到过,该列的数据类型是int,但它也包含 DBNull 值。放置断点并检查是我做的第一件事。这是我已经交叉验证的 DBNull
    猜你喜欢
    • 1970-01-01
    • 2020-10-05
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-15
    相关资源
    最近更新 更多