C#中“标准表达式中的数据类型不匹配”

时间:2013-07-07 02:49:58

标签: c# oledb

我在字符串变量中有一个数字“userID”。我将其转换为int以从数据库获取“用户名”和“角色”,该数据库具有带有AutoNumber数据类型的“user_ID”字段。转换后的userID被分配给变量“value”。但是我在行中得到“条件表达式中的数据类型不匹配”:

OleDbDataReader roleReader = command.ExecuteReader();

这是完整的代码

class HomeClass
{
    string userID;
    string role;
    string username;

    public HomeClass(string myUserID)
    {
        userID = myUserID;
    }

    public string checkRole()
    {
        int value;
        value = Int32.Parse(userID);
        string query = "SELECT role FROM userAccounts WHERE user_ID = '" + value + "'";
        ConnectDatabaseString myConnectionString = new ConnectDatabaseString();
        OleDbConnection connection = new OleDbConnection();
        connection.ConnectionString = myConnectionString.connect();
        connection.Open();

        OleDbCommand command = new OleDbCommand();
        command.Connection = connection;
        command.CommandText = query;
        OleDbDataReader roleReader = command.ExecuteReader();
        roleReader.Read();
        role = roleReader["roles"].ToString();
        return role;
    }

    public string getUsernameToBeShown()
    {
        int value;
        value = Int32.Parse(userID);
        string query = "SELECT username FROM userAccounts WHERE user_ID = '" + value + "'";
        ConnectDatabaseString myConnectionString = new ConnectDatabaseString();
        OleDbConnection connection = new OleDbConnection();
        connection.ConnectionString = myConnectionString.connect();
        connection.Open();

        OleDbCommand command = new OleDbCommand();
        command.Connection = connection;
        command.CommandText = query;
        OleDbDataReader usernameReader = command.ExecuteReader();
        usernameReader.Read();
        username = usernameReader["username"].ToString();
        return username;
    }
}

此错误的根本原因是什么?

2 个答案:

答案 0 :(得分:1)

您在SQL查询中使用字符串文字。 EG 'value' '表示数据类型是字符串。删除它,你不应该有任何问题。

答案 1 :(得分:0)

在您的SQL语句中,您将user_ID字符串文字(引号)进行比较。

您想将其与数字进行比较。