【发布时间】:2016-05-11 03:22:36
【问题描述】:
我有一个应用程序,当单击按钮时,它会读取产品的访问数据库并将它们列在列表框和 dataGridView 中。连接命令文本为northwind_command.CommandText = "SELECT ProductName, UnitPrice FROM Products WHERE UnitPrice > (@price_greater_than)";
在第一次单击时程序会运行,但当第二次单击按钮时会引发异常。由于此引发的异常会导致数据读取器“崩溃”,因此第三次单击将像第一次一样工作。第四次点击会抛出同样的异常。如果我不得不猜测,我会说数据读取器没有正确关闭,但它应该是。以下是该部分程序的代码:
northwind_connection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='U:\Programming\C#\Week 13\Exercises\ExerciseA1\bin\northwind.mdb';Persist Security Info=True";
northwind_command.Connection = northwind_connection; // connects the command to the connection.
northwind_command.CommandText = "SELECT ProductName, UnitPrice FROM Products WHERE UnitPrice > (@price_greater_than)"; // sets the query used by this command.
northwind_command.Parameters.AddWithValue("@price_greater_than", price_greater_than);
try
{
northwind_connection.Open(); // opens the connection.
northwind_reader = northwind_command.ExecuteReader(); // reads the data from the connection while executing the command.
dataGridView1.Columns.Add("ProductName", "Product Name");
dataGridView1.Columns.Add("UnitPrice", "Product Price");
while (northwind_reader.Read())
{
dataGridView1.Rows.Add(northwind_reader["ProductName"], northwind_reader["UnitPrice"]);
listBox1.Items.Add(northwind_reader["ProductName"] + "\t" + northwind_reader["UnitPrice"]);
}
}catch(Exception mistake)
{
MessageBox.Show(mistake.ToString());
}
northwind_connection.Close();
编辑:我已经在一些帮助下解决了这个问题,但想首先弄清楚它为什么会发生。违规行是northwind_command.Parameters.AddWithValue("@price_greater_than", price_greater_than);。上面那一行被修改为:northwind_command.CommandText = "SELECT ProductName, UnitPrice FROM Products WHERE UnitPrice > " + price_greater_than;,程序现在可以正常工作了。
我检查了异常消息,第 50 行包含以下代码:northwind_reader = northwind_command.ExecuteReader();,它确认 AddwithValue 方法导致了错误。
【问题讨论】:
-
向我们展示异常/错误消息
-
@Irfan 如果他将
Close()放在while(){...}之后,并且在该循环中或try{}子句中的任何地方引发异常,则连接将永远不会关闭。当他创建连接时,它应该在using中完成,或者如果他不想这样做,它应该在finally{}子句中。
标签: c# datagridview oledb