如何在sql中检查值是1还是0?

6mzjoqzu  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(512)

所以我设置了我的数据库连接,它确实连接了。现在我要检查表中的每一行 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;
    }
}
tct7dpnv

tct7dpnv1#

我想你在找这样的东西:

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

yr9zkbsy

yr9zkbsy2#

如果要读取字段,可以实现如下操作:

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

w8f9ii693#

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
}

相关问题