默认情况下,返回的DataReader即使执行了DataReader.Close()。其对应的Connection还是打开着的,而按照Access那点性能,页面刷新多几下就出错了。而且本地不会出错,上传到服务器才会出错,很是能搞死人!
查了很多资料,得出一个返回Reader的方法。这个方法返回的Reader只要执行了Close()。其对应的Connection也会随之关闭。话不多说,方法奉上:
/// <summary>
/// 执行查询语句,返回OleDbDataReader
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>OleDbDataReader</returns>
public static OleDbDataReader ExecuteReader(string strSQL)
{
OleDbConnection connection = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand(strSQL, connection);
connection.Open();
OleDbDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
重点在cmd.ExecuteReader的时候,传入一个参数:CommandBehavior.CloseConnection。这样返回的Reader只要执行了Close,就可以关闭Connection了~