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

时间:2016-05-11 03:22:37

标签: c# datagridview oledb

我有一个应用程序,当单击一个按钮时,它会读取产品的访问数据库并将它们列在listbox和dataGridView中。连接命令文本为northwind_command.CommandText = "SELECT ProductName, UnitPrice FROM Products WHERE UnitPrice > (@price_greater_than)";

在第一次单击时,程序将起作用,但是当第二次单击该按钮时会抛出异常。由于这个抛出的异常导致数据读取器崩溃",第三次点击将像第一次点击一样工作。第四次单击将抛出相同的异常。如果我不得不猜测,我会说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_command.Parameters.AddWithValue("@price_greater_than", price_greater_than);。上面一行被修改为:northwind_command.CommandText = "SELECT ProductName, UnitPrice FROM Products WHERE UnitPrice > " + price_greater_than;,程序现在可以正常工作。

该方法导致抛出异常,如下所示:enter image description here

我检查了异常消息,第50行包含此代码:northwind_reader = northwind_command.ExecuteReader();,确认AddwithValue方法导致错误。

3 个答案:

答案 0 :(得分:2)

我敢打赌,事情没有得到妥善处理。尝试修改代码以使用using语句:

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时,你真的应该将它包装在using语句中。这样做可确保所有资源得到妥善处理。对于数据库连接,这将确保您的连接已关闭,因此无需致电myConn.Close()

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

编辑: 既然您发现问题出在AddWithValue,请允许我添加:

根据过去的经验,我在使用@paramName OleDbCommand语法时遇到了问题。请尝试使用?paramNam语法。如果名字很长,我也有问题,所以试着缩短它。

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

答案 1 :(得分:1)

northwind_reader.Close()循环结束时添加while

答案 2 :(得分:0)

您需要在再次使用之前关闭阅读器。

示例:

while (reader.Read())
{
string value = reader.GetValue(0).tostring();
}
reader.Close();
在您的情况下,

是northwind_command.close()

相关问题