簡體   English   中英

C#中的“條件表達式中的數據類型不匹配”

[英]“Data type mismatch in criteria expression” in C#

我在字符串變量中有一個數字“ userID”。 我將其轉換為int以從具有“自動編號”數據類型的“ user_ID”字段的數據庫中獲取“用戶名”和“角色”。 轉換后的用戶ID分配給變量“值”。 但是我在行中看到“條件表達式中的數據類型不匹配”:

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

此錯誤的根本原因是什么?

您在SQL查詢中使用字符串文字。 EG'value 'value' '表示數據類型是字符串。 刪除它,您應該不會有任何問題。

在您的SQL語句中,您正在將user_ID字符串文字(用引號引起來)進行比較。

您想將其與數字進行比較。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM