Amrit Sharma
Amrit Sharma

Reputation: 1916

Checking value of YES/NO datatype in Access

In one of of table, I have field that stores the value in YES/NO data type.

I am trying to check the value of the field using the following query but receiving error as shown in the picture below.

public string getAccess(string username)
        {
            // Create connection object
            OleDbConnection oleConn = new OleDbConnection(connString);
            oleConn.Open();
            string sql = "SELECT [admin] FROM [Users] WHERE [username]='" + username + "'";
            OleDbCommand cmd = new OleDbCommand(sql, oleConn);
            string x = (string)cmd.ExecuteScalar();


            oleConn.Close();


            return x;
        }

The field admin is in YES/NO type data field.

enter image description here

How can i check the value of the data type? Please correct by query if wrong?

Upvotes: 0

Views: 1624

Answers (2)

Karl Anderson
Karl Anderson

Reputation: 34844

The yes/no field in Access is equivalent to the bit field type in SQL Server, so I believe you should be returning a Boolean from your method instead of a string, try something like this:

public bool isAdmin(string username)
{
    // Create connection object
    OleDbConnection oleConn = new OleDbConnection(connString);
    oleConn.Open();
    string sql = "SELECT [admin] FROM [Users] WHERE [username]='" + username + "'";
    OleDbCommand cmd = new OleDbCommand(sql, oleConn);
    bool x = (bool)cmd.ExecuteScalar();

    oleConn.Close();

    return x;
}

Or if you are determined to have string be the return value, then this:

public string getAccess(string username)
{
    // Create connection object
    OleDbConnection oleConn = new OleDbConnection(connString);
    oleConn.Open();
    string sql = "SELECT [admin] FROM [Users] WHERE [username]='" + username + "'";
    OleDbCommand cmd = new OleDbCommand(sql, oleConn);
    bool x = (bool)cmd.ExecuteScalar();

    oleConn.Close();

    return x ? "Yes" : "No";
}

Upvotes: 2

Amrit Sharma
Amrit Sharma

Reputation: 1916

Changed method type to bool and it works

public bool getAccess(string username)
        {
            // Create connection object
            OleDbConnection oleConn = new OleDbConnection(connString);
            oleConn.Open();
            string sql = "SELECT [admin] FROM [Users] WHERE [username]='" + username + "'";
            OleDbCommand cmd = new OleDbCommand(sql, oleConn);
            bool x = (bool)cmd.ExecuteScalar();


            oleConn.Close();


            return x;
        }

Upvotes: 1

Related Questions