例如我有这个代码:
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)
是否释放了datareader使用的Cursor?还是会保持开放?
如果datareader使用的光标仍处于打开状态,何时自动关闭?或者我应该手动关闭它?
是否会导致可怕的“ORA-01000:超出最大打开游标数”?
提前致谢
答案 0 :(得分:1)
CommandBehavior.CloseConnection
将上述值作为参数传递给ExecuteReader时 1.当您关闭阅读器时,无需关闭连接显式连接
查看完整帖子:http://pranayamr.blogspot.com/2010/11/executereader-with-commanbehavior.html
答案 1 :(得分:1)
您应该在使用块中创建对象,以便正确处理它们:
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
无需在连接或datareader上调用Close。
答案 2 :(得分: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();
}
答案 3 :(得分:0)
为什么不这样明确地关闭读者。
datareader.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