简体   繁体   中英

List.Count always returns 0

I'm creating a public static List<> of variables (from MySQL query) but the List 's Count always returns 0 ! I've tried everything so far but no success. Here is my code:

public static List<string> GetHashedVars(string ID)
{
    List<string> lst = new List<string>();
    MySqlConnection conn;
    MySqlCommand cmd;
    MySqlDataReader reader;
    string connString, queryStr = "";
    connString = ConfigurationManager.ConnectionStrings["GameserverConnString"].ToString();
    using (conn = new MySqlConnection(connString))
    {
        //The query for execution
        queryStr = "SELECT * FROM account.account WHERE id_hashed=?hid LIMIT 1";
        //Open the connection to the database
        conn.Open();
        //execute command
        cmd = new MySqlCommand(queryStr, conn);
        cmd.Parameters.AddWithValue("?hid", ID);
        using (reader = cmd.ExecuteReader())
        {
            //Loop through results
            while (reader.Read())
            {
                lst.Add(reader.GetString(reader.GetOrdinal("id_hashed")));
                lst.Add(reader.GetString(reader.GetOrdinal("login_hashed")));
                lst.Add(reader.GetString(reader.GetOrdinal("webcode_hashed")));
                lst.Add(Encryption.CipherEncryption(reader.GetString(reader.GetOrdinal("status")).Trim()));
            }
        }
        reader.Close();
        conn.Close();
    }
    queryStr = "";
    reader = null;
    cmd = null;
    conn = null;
    connString = "";
    return lst;
}

Looks like you are using named parameters but do not set your parameters correctly.

? is used for non named parameters and @ are used for named parameters. Since the database connector you are using does not support non named parameters you have to follow the convention using the @ in your query. This will set the parameters by name rather than by index.

queryStr = "SELECT * FROM account.account WHERE id_hashed=@hid LIMIT 1";
...
cmd.Parameters.AddWithValue("@hid", ID);

Explanation from msdn .

The Microsoft .NET Framework Data Provider for SQL Server does not support the question mark (?) placeholder for passing parameters to a SQL Statement or a stored procedure called by a command of CommandType.Text. In this case, named parameters must be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM