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

时间:2018-07-25 08:29:43

标签: c# mysql sql .net

因此,我已经建立了数据库连接,并且确实可以连接。 现在,我想检查表中的每一行,因为列isactivated0还是1是因为它是 bit ,但是我不知道如何做吧。

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

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

3 个答案:

答案 0 :(得分:3)

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
}

答案 1 :(得分:0)

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

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列,然后您可以检查其各自的值。

答案 2 :(得分:0)

如果您想阅读该字段,则可以执行以下操作:

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