【问题标题】:Reading from a Database throws exception on second attempt?从数据库读取第二次尝试抛出异常?
【发布时间】: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


【解决方案1】:

我敢打赌,有些东西没有得到妥善处理。尝试修改您的代码以使用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 必须解释列的类型,有时会出错。

【讨论】:

  • 我已经检查过了,dataGridView 列没问题。毫无疑问,这是由 AddWithValue 方法引起的,因为修改该部分以避免使用该方法已解决了该问题。
  • @SpaceOstrich 查看我的编辑。它们可能无法解决您的问题,但它们是一些更好的编码实践。
【解决方案2】:

while 循环的末尾添加northwind_reader.Close()

【讨论】:

  • 如果他将Close() 放在while(){...} 之后,并且在该循环中或try{} 子句中的任何地方引发异常,则连接将永远不会关闭。当他创建连接时,它应该在using 中完成,或者如果他不想这样做,它应该在finally{} 子句中。
  • 注明。谢谢你。我更喜欢using
【解决方案3】:

您需要关闭阅读器才能再次使用它。

示例:

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

在你的情况下是 northwind_command.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多