繁体   English   中英

如何检查SQL中的值是1还是0?

[英]How do I check whether a value is 1 or 0 in SQL?

因此,我已经设置了数据库连接,并且它确实连接了。 现在,我想检查表中的每一行,是否已isactivated该列是0还是1因为有点,但是我不知道该怎么做。

我会执行查询吗? 是否将所有行存储在列表中,然后检查?

using (var connection = new SqlConnection(cb.ConnectionString))
{
    try
    {
        connection.Open();
        if (connection.State == ConnectionState.Open)
        {
            Console.WriteLine("Connected!");
        }
        else
        {
            Console.WriteLine("Failed..");
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }
}
SqlCommand command = new SqlCommand("SELECT column FROM table", connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
    // 0 = false, 1 = true,
    bool result = (bool)reader[0];

    //... do whatever you wanna do with the result
}

我认为您正在寻找这样的东西:

SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;

cmd.CommandText = "SELECT * FROM Customers";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;

sqlConnection1.Open();

reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.

sqlConnection1.Close();

取自msdn-lib

在SqlDataReader中应该是所有数据,包括isactivated列,然后可以检查其各自的值。

如果您想阅读该字段,则可以实现以下内容:

  using (var connection = new SqlConnection(cb.ConnectionString)) {
    try {
      connection.Open();

      // connection.Open() either succeeds (and so we print the message) 
      // or throw an exception; no need to check 
      Console.WriteLine("Connected!");

      //TODO: edit the SQL if required
      string sql =
        @"select IsActivated
            from MyTable";

      using (var query = new SqlCommand(sql, connection)) {
        using (var reader = query.ExecuteReader()) {
          while (reader.Read()) {
            // Now it's time to answer your question: let's read the value 
            //   reader["IsActivated"] - value of IsActivated as an Object
            //   Convert.ToBoolean     - let .Net do all low level work for you
            bool isActivated = Convert.ToBoolean(reader["IsActivated"]);

            // Uncomment, if you insist on 0, 1
            // int bit = Convert.ToInt32(reader["IsActivated"]);

            //TODO: field has been read into isActivated; put relevant code here  
          }
        }
      }
    }
    catch (DataException e) { // Be specific: we know how to process data errors only
      Console.WriteLine(e);

      throw;
    }
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM