从数据库读取布尔值? [英] Read boolean values from DB?

查看:280
本文介绍了从数据库读取布尔值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,使用SqlDataReader,有没有办法从数据库中读取布尔值?

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

while (reader.Read())
{
    destPath = reader["destination_path"].ToString();
    destFile = reader["destination_file"].ToString();
    createDir = reader["create_directory"].ToString();
    deleteExisting = Convert.ToBoolean(reader["delete_existing"]);
    skipIFolderDate = reader["skipifolderdate"].ToString();
    useTempFile = reader["useTempFile"].ToString();
    password = reader["password"].ToString();
}

在上面的代码中,delete_existing在数据库中始终为1或0。我在MSDN上读到Convert.ToBoolean()不接受1或0作为有效输入。它仅接受对或错。是否有将DB值转换为布尔值的替代方法?还是我需要在SqlDataReader之外执行此操作?

In the code above, delete_existing is always a 1 or 0 in the DB. I read on MSDN that Convert.ToBoolean() does not accept a 1 or 0 as valid input. It only accepts true or false. Is there an alternative way to convert a DB value to a bool? Or do I need to do this outside of the SqlDataReader?

此外,我无法更改数据库值,因此请不要回答:将数据库值从1更改为和0分别为true和false。

Also, I can not change the DB values, so please no answers saying, "Change the DB values from 1's and 0's to true's and false's."

谢谢!

推荐答案

如果 delete_existing 的类型是sqlserver位类型,则可以执行以下操作:

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);

或(但如果 delete_existing ,它将崩溃可以是 DBNull

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

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

或更好,以下是 DBNull 证明如果列为 DBNull

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

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

否则,如果数据库类型为 int

Otherwise if the database type is int :

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

或者如果它是 varchar

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

这篇关于从数据库读取布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆