Reputation: 1057
So I've setup my database connection and it does connect.
Now I want to check each row in my table whether the column isactivated
is either 0
or 1
because it's a bit but I don't know how to do it.
Would I execute a query? Would I store all the rows in a list and then check?
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;
}
}
Upvotes: 0
Views: 519
Reputation: 186793
If you want to read the field you can implement something like this:
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;
}
}
Upvotes: 0
Reputation: 116
I think you are looking for something like this:
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();
Taken from msdn-lib.
In the SqlDataReader should be all your data including your isactivated column, which you then can check for its respective values.
Upvotes: 0
Reputation: 51
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
}
Upvotes: 3