C# 从数据库读取在第二次尝试时引发异常?

C# 从数据库读取在第二次尝试时引发异常?,c#,datagridview,oledb,C#,Datagridview,Oledb,我有一个应用程序,当点击一个按钮时,它会读取产品的access数据库,并在listbox和dataGridView中列出它们。连接命令文本为northwind\u command.CommandText=“从UnitPrice>所在的产品中选择产品名称、单价”(@price\u大于)” 在第一次单击时,程序将工作,但在第二次单击按钮时,将引发异常。由于这个抛出的异常导致数据读取器“崩溃”,第三次单击将像第一次一样工作。第四次单击将引发相同的异常。如果非要我猜的话,我会说datareader没有正

我有一个应用程序,当点击一个按钮时,它会读取产品的access数据库,并在listbox和dataGridView中列出它们。连接命令文本为
northwind\u command.CommandText=“从UnitPrice>所在的产品中选择产品名称、单价”(@price\u大于)”

在第一次单击时,程序将工作,但在第二次单击按钮时,将引发异常。由于这个抛出的异常导致数据读取器“崩溃”,第三次单击将像第一次一样工作。第四次单击将引发相同的异常。如果非要我猜的话,我会说datareader没有正确关闭,但它应该关闭。以下是该部分程序的代码:

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\u命令.Parameters.AddWithValue(“@price\u大于”,price\u大于)。该行上方的行被修改为:
northwind\u command.CommandText=“从UnitPrice>所在的产品中选择产品名称、单价”+price\u大于和程序现在可以正常工作

该方法导致引发异常,如下所示:


我检查了异常消息,第50行包含以下代码:
northwind\u reader=northwind\u command.ExecuteReader()
,它确认了
AddwithValue
方法是导致错误的原因。

while
循环结束时添加
northwind\u reader.Close()

我敢打赌有些东西没有得到正确处理。尝试使用
语句修改代码以使用

using(var northwindConnection = new OleDbConnection())
{
    //Set your connection info

    using(var northwindCommand = northwindConnection.CreateCommand())
    {
        //Set your command info

        try
        {
            // Open your connection and any other things 
            // needed before executing your reader
            using(var reader = northwindCommand.ExecuteReader()){
                //Do what you need with your reader
            }
        }
        catch(Exception mistake)
        {
            MessageBox.Show(mistake.ToString());
        }
    }
}
当一个类实现了
IDisposable
时,您确实应该使用
语句将其包装在
中。这样做将确保所有资源得到适当的配置。对于数据库连接,这将确保您的连接已关闭,因此无需调用
myConn.Close()

另一个可能导致问题的原因是,每次单击按钮时,都会向
dataGridView1
添加列

编辑: 因为您发现问题出在
AddWithValue
上,所以让我添加以下内容:

在过去的经验中,我在将
@paramName
语法与
OleDbCommand
一起使用时遇到过问题。尝试改用
?paramNam
语法。如果名字太长,我也会遇到问题,所以试着缩短它


您应该使用
Paramaters.Add(string,OleDbType).Value=Value
而不是
Paramaters.AddWithValue(string,Value)
。原因是,
AddWithValue
必须解释列的类型,有时可能会出错。

再次使用之前,需要关闭读卡器

例如:

while (reader.Read())
{
string value = reader.GetValue(0).tostring();
}
reader.Close();

在您的例子中是northwind_命令。close()

显示异常/错误message@Irfan如果他将
Close()
放在
while(){…}
之后,并且在该循环中或
try{}
子句中的任何位置引发异常,则连接将永远不会关闭。当他创建连接时,应该在
中使用
,或者如果他不想这样做,应该在
finally{}
子句中进行。我已经检查过了,dataGridView列也没有问题。毫无疑问,这是由AddWithValue方法引起的,因为修改该部分以避免使用该方法已修复了该问题。@SpaceOstrich请参阅我的编辑。它们可能无法解决您的问题,但它们是一些更好的编码实践。如果他将
Close()
放在
while(){…}
之后,并且在该循环中或
try{}
子句中的任何位置抛出异常,则连接将永远不会关闭。当他创建连接时,应该在
中使用
,或者如果他不想这样做,应该在
finally{}
子句中完成。注意。非常感谢。我更喜欢通过
使用
来做。