[英]MySQL C# Error; “connection must be valid and open”
您好,我得到了我正在處理的該應用程序,但仍無法填充下拉框。 我想從下拉列表中的數據庫中獲取我的SQL數據,但是SQL表示“連接必須有效且打開”,但是我得到了另一個功能,該功能包括使用相同的代碼將文本保存到SQL數據庫中,並且可以正常工作,所以我不這樣做真的不知道怎么了。
這是我的代碼。
private void Form1_Load(object sender, EventArgs e)
{
try {
//This is my connection string i have assigned the database file address path
string MyConnection2 = "datasource=localhost;username=root;database=game4rent";
//This is my insert query in which i am taking input from the user through windows forms
string Query = "select Klantnummer,voornaam from game4rent.klanten";
//This is MySqlConnection here i have created the object and pass my connection string.
MySqlConnection conn = new MySqlConnection(MyConnection2);
//This is command class which will handle the query and connection object.
MySqlCommand sc = new MySqlCommand(Query, conn);
MySqlDataReader MyReader2;
MyReader2 = sc.ExecuteReader();
conn.Open();
DataTable dt = new DataTable();
dt.Columns.Add("Klantnummer", typeof(string));
dt.Columns.Add("voornaam", typeof(string));
dt.Load(MyReader2);
cbKlantenNummers.ValueMember = "Klantnummer";
cbKlantenNummers.DisplayMember = "Klantnummer,voornaam";
cbKlantenNummers.DataSource = dt;
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
這是其他起作用的代碼。
private void cmdOpslaanKlanten_Click(object sender, EventArgs e)
{
try
{
//This is my connection string i have assigned the database file address path
string MyConnection2 = "datasource=localhost;username=root;password=";
//This is my insert query in which i am taking input from the user through windows forms
string Query = "insert into game4rent.klanten(voornaam,achternaam,straat,huisnummer,woonplaats) values('" + this.txtVoornaam.Text + "','" + this.txtAchternaam.Text + "','" + this.txtStraat.Text + "','" + this.txtHuisnummer.Text + "','" + this.txtWoonplaats.Text + "');";
//This is MySqlConnection here i have created the object and pass my connection string.
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
//This is command class which will handle the query and connection object.
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader(); // Here our query will be executed and data saved into the database.
MessageBox.Show("Save Data");
while (MyReader2.Read())
{
}
MyConn2.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
您正在嘗試在打開連接之前執行查詢:
MyReader2 = sc.ExecuteReader();
conn.Open();
由於錯誤狀態,必須在執行查詢之前打開連接:
conn.Open();
MyReader2 = sc.ExecuteReader();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.