簡體   English   中英

使用SELECT查詢時,mscorlib.dll中引發異常:“ System.Collections.Generic.KeyNotFoundException”

[英]Exception thrown: 'System.Collections.Generic.KeyNotFoundException' in mscorlib.dll when using a SELECT query

try
{
    string connString = "server=db4free.net;port=3306;database=secretdb;user id=secret;password=secret;charset=utf8";
    MySqlConnection conn = new MySqlConnection(connString);
    conn.Open();
    MySqlCommand cmd = new MySqlCommand("SELECT School_Name FROM schools WHERE School_ID=@id", conn);
    cmd.Parameters.AddWithValue("@id", "1");
    var schoolName = cmd.ExecuteScalar();
    label1.Text = schoolName.ToString();
    conn.close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

上面的代碼返回拋出的異常Exception:mscorlib.dll中的“ System.Collections.Generic.KeyNotFoundException”

但是,每當我使用諸如INSERT,UPDATE和DELETE之類的查詢時,它就可以正常工作 就像下面的代碼:

try
{
    string connString = "server=db4free.net;port=3306;database=secretdb;user id=secret;password=secret;charset=utf8";
    MySqlConnection conn = new MySqlConnection(connString);
    conn.Open();
    MySqlCommand cmd = new MySqlCommand("INSERT INTO schools(School_Name,School_Address) VALUES(@name,@address)", conn);
    cmd.Parameters.AddWithValue("@name", "Sample Name");
    cmd.Parameters.AddWithValue("@address", "Sample Address");
    cmd.ExecuteNonQuery();
    label1.Text = "Success";
    conn.Close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

所以基本上我的問題是:

  1. 如果在Xamarin.Forms (在Android中測試)中使用, 第一段代碼就可以正常工作。 我可以從數據庫中選擇。
  2. 如果在Windows Forms App中使用,則第一段代碼不起作用,並返回上述異常。 Xamarin.Forms和Windows Forms App均在C#上運行,因此我不完全知道為什么會這樣。
  3. 第二段代碼在Xamarin.FormsWindows Forms App中都可以正常工作。
  4. 基本上,我可以運行任何SQL查詢,但不能運行SELECT。

首先,如果發生異常,您的代碼可以使連接保持打開狀態。 conn.Close()應該移動到finally塊。 其次,要查詢​​值,您應該使用cmd.ExecuteReader()方法,該方法將返回MySqlDataReader對象。 要處理它,可以使用using()構造。 ExecuteScalar()方法用於插入/更新/刪除語句,並返回受影響的行數。

第三,但同樣重要:考慮將與數據庫相關的代碼移至Repository類,然后從Form邏輯中調用您的存儲庫類代碼。 這樣,您將獲得一段可重用的代碼。 存儲庫類起點的簡單示例:

public class Repository
{
    public string ConnectionString { get; private set; }

    public Repository(string connectionString)
    {
        this.ConnectionString = connectionString;
    }

    public string GetSchoolNameById(int id)
    {
        string schoolName = null;
        MySqlConnection conn = null;
        try
        {
            conn = new MySqlConnection(this.ConnectionString);
            conn.Open();
            using (MySqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandText = "SELECT School_Name FROM schools WHERE School_ID=@id";
                cmd.Parameters.AddWithValue("@id", id);
                using (var rdr = cmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        if (!rdr.IsDBNull(rdr.GetOrdinal("School_Name")))
                        {
                            schoolName = rdr.GetString(rdr.GetOrdinal("School_Name"));
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            // maybe log exception here, or rethrow it if you want
            // the consumer to manage it. This depends on how you plan to build your software architecture.
        }
        finally
        {
            // this code will run always, either if everything ran correctly or if some exception occurred in the try block.
            if (conn != null)
            {
                conn.Close();
                conn.Dispose();
            }
        }
        return schoolName;
    }

}

然后,您的表單代碼可以很簡單:

    Repository rep = new Repository("server=db4free.net;port=3306;database=secretdb;user id=secret;password=secret;charset=utf8");
    try
    {
        // the try/catch is necessary if you have decided to re-throw the exception in the Repository.GetSchoolNameById method
        label1.Text = rep.GetSchoolNameById(1);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

暫無
暫無

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

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