4

例如我有这个代码:

Sub Month()
    Dim Conn As New Data.OracleClient.OracleConnection
    Conn.Open()
    Try

        Dim Cmd As New Data.OracleClient.OracleCommand
        With Cmd
            .Connection = Conn
            .CommandType = Data.CommandType.Text
            .CommandText = "SELECT * FROM MONTH"
        End With
        Dim datareader As Data.OracleClient.OracleDataReader = Cmd.ExecuteReader
        While datareader.Read
            Response.Write(datareader(0))
        End While
    Catch ex As Exception
        Throw ex
    Finally
        Conn.Close()
    End Try
End Sub

当连接关闭时数据读取器会发生什么(Conn.close)

数据读取器使用的光标会被释放吗?还是会保持开放?

如果数据读取器使用的游标仍然打开,什么时候会自动关闭?还是我应该手动关闭它?

它会导致可怕的“ORA-01000:超出最大打开游标”吗?

提前致谢

4

4 回答 4

2

您应该在 using 块中创建对象,以便正确处理它们:

Using Conn As New Data.SqlClient.SqlConnection
    Conn.Open()

    Dim Cmd As New Data.SqlClient.SqlCommand
    With Cmd
        .Connection = Conn
        .CommandType = Data.CommandType.Text
        .CommandText = "SELECT * FROM MONTH"
    End With

    Using datareader As Data.SqlClient.SqlDataReader = Cmd.ExecuteReader()
        While datareader.Read()
            Response.Write(datareader(0))
        End While
    End Using
End Using

无需在连接或数据读取器上调用 Close。

于 2011-05-31T16:36:18.627 回答
1

关闭后只需创建数据读取器的新对象

private void button2_Click(object sender, EventArgs e)
    {
        //SqlConnection cn1 = new SqlConnection();
        cn.ConnectionString = "server = .\\SQLEXPRESS ; database=store ; integrated security = true  ";
        SqlCommand cm = new SqlCommand("select * from emp", cn);
        cn.Open();
        SqlDataReader dr = cm.ExecuteReader();
        DataTable dt = new DataTable();
        dt.Load(dr);
        dataGridView1.DataSource = dt.DefaultView ;
        //SqlCommand cm3 = new SqlCommand("select * from emp", cn1);
        SqlDataReader dr1 = cm.ExecuteReader();
        listBox1.Items.Clear();
        while (dr1.Read())
        {
            //listBox1.Items.Add(dr.GetString(2));
            listBox1.Items.Add(dr1["name"]);

        }
        cn.Close();
    }
于 2012-10-23T09:50:31.100 回答
1
CommandBehavior.CloseConnection

当您将上述值作为参数传递给 ExecuteReader 1. 当您关闭阅读器时,无需显式关闭连接

查看完整帖子: http: //pranayamr.blogspot.com/2010/11/executereader-with-commanbehavior.html

于 2011-05-31T04:03:41.260 回答
0

为什么不应该像这样明确地关闭阅读器。

数据读取器.Close()

Dim Conn As New Data.SqlClient.SqlConnection
Conn.Open()
Try

    Dim Cmd As New Data.SqlClient.SqlCommand
    With Cmd
        .Connection = Conn
        .CommandType = Data.CommandType.Text
        .CommandText = "SELECT * FROM MONTH"
    End With
    Dim datareader As Data.SqlClient.SqlDataReader = Cmd.ExecuteReader
    While datareader.Read
        Response.Write(datareader(0))
    End While
    datareader.Close()
Catch ex As Exception
    Throw ex
Finally
    Conn.Close()
End Try
于 2011-05-31T05:13:05.020 回答