Read boolean values from DB?

后端 未结 5 849
时光说笑
时光说笑 2020-12-16 15:07

In C#, using SqlDataReader, is there a way to read a boolean value from the DB?

while (reader.Read())
{
    destPath = reader[\"destination_path\"].ToString(         


        
相关标签:
5条回答
  • 2020-12-16 15:23

    How about this?

    deleteExisting = (reader["delete_existing"] as int?) == 1;
    

    Boolean is probably the easist type to convert something to. Here's the 'Y', 'N' version:

    deleteExisting = string.Equals(reader["delete_existing"] as string, "Y", StringComparision.OrdinalIgnoreCase);
    
    0 讨论(0)
  • 2020-12-16 15:34

    If you are using CASE in SELECT and want to use GetBoolean then use CAST to change the column to bit before reading.

    For eg:

    SELECT CAST((CASE WHEN [Condition] THEN 1 ELSE 0 END) as bit) FROM Table_Name
    

    then you can use

    reader.GetBoolean(0)
    
    0 讨论(0)
  • 2020-12-16 15:43

    If the type of delete_existing is a sqlserver 'bit' type, you can do :

    var i = reader.GetOrdinal("delete_existing"); // Get the field position
    deleteExisting = reader.GetBoolean(i);
    

    or (but it will crash if delete_existing can be DBNull)

    deleteExisting = (bool)reader["delete_existing"];
    

    or better, this onebelow is DBNull proof and returns false if the column is DBNull

    deleteExisting = reader["delete_existing"] as bool? ?? false;
    

    Otherwise if the database type is int :

    deleteExisting = (reader["delete_existing"] as int? == 1) ? true : false;
    

    or if it is a varchar

    deleteExisting = (reader["delete_existing"] as string == "1") ? true : false;
    
    0 讨论(0)
  • 2020-12-16 15:44
    deleteExisting = reader.GetBoolean(reader["delete_existing"]);
    
    0 讨论(0)
  • 2020-12-16 15:45

    Casting works: myVar = (bool)dataReader["myColumn"];

    0 讨论(0)
提交回复
热议问题