private static SqlConnection Sqlconnection;
public static SqlConnection SqlConnection
{
get
{
string SqlconnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["TandyTang"].ToString();
if (Sqlconnection == null)
{
Sqlconnection = new SqlConnection(SqlconnectionString);
Sqlconnection.Open();
}
else if (Sqlconnection.State == System.Data.ConnectionState.Closed)
{
Sqlconnection.Open();
}
else if (Sqlconnection.State == System.Data.ConnectionState.Broken)
{
Sqlconnection.Close();
Sqlconnection.Open();
}
return Sqlconnection;
}
}
///<summary>
/// SqlGetDataTable
///<param name="proc"></param>
///<param name="type"></param>
///<param name="param"></param>
///<param name="count"></param>
///<returns>DataTable</returns>
public static DataTable SqlGetDataTable(string proc, CommandType type, string[] param, out int count)
{
DataSet ds = new DataSet();
using (SqlCommand cmd = new SqlCommand(proc, SqlConnection))
{
SqlParameter[] myParms = new SqlParameter[2];
myParms[0] = new SqlParameter("@Id", SqlDbType.Int, 4);
myParms[0].Value = paramValue[0];
myParms[1] = new SqlParameter("@Name", SqlDbType.VarChar, 50);
myParms[1].Value = paramValue[1];
foreach (SqlParameter parameter in myParms)
{
cmd.Parameters.Add(parameter);
}
cmd.CommandType = type;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
}
return ds.Tables[0];
}
以上代碼,我相信在一般人看來,應該都沒問題,我也認為沒什么問題。第一段代碼是創建數據連接,并打開數據庫連接,第二段代碼是創建一個SqlCommand,其中要用到SqlConnection作為第一個參數,這就是問題的關鍵。
如果在頁面上值運行一遍SqlGetDataTable()方法就不會出任何問題,如果不停的頁面的刷新頁面就“已有打開的與此命令相關聯的DataReader,必須首先將它關閉。”這樣的異常(也許不會出現哦,你試試就知道了。代碼紅色字體部分就是出現錯誤提示的地方)
經過我的思考,終于找到了解決的辦法,解決辦法如下,看下面代碼:
代碼如下:
private static string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["TandyTang"].ConnectionString;
///<summary>
/// SqlGetDataTable
///<param name="proc"></param>
///<param name="type"></param>
///<param name="param"></param>
///<param name="count"></param>
///<returns>DataTable</returns>
public static DataTable SqlGetDataTable(string proc, CommandType type, string[] param, out int count)
{
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(proc, con))
{
SqlParameter[] myParms = new SqlParameter[11];
myParms[0] = new SqlParameter("@Id", SqlDbType.Int, 4);
myParms[0].Value = paramValue[0];
myParms[1] = new SqlParameter("@Name", SqlDbType.VarChar, 50);
myParms[1].Value = paramValue[1];
foreach (SqlParameter parameter in myParms)
{
cmd.Parameters.Add(parameter);
}
cmd.CommandType = type;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(ds);
}
}
return ds.Tables[0];
}
}
應該發現有什么不同的地方了吧,上面的方法,沒用用到SqlConnection方法,而是把SqlConnection對象寫到using(){}里面的。
PS:個人建議大家不要用第一種方法,也許會遇到很的麻煩的哦,個人建議多用using(){}語句把ADO.NET的沒對象都放到using(){}里面最好了,using(){}的好處我想大家也都知道,所以我也不做過多的解釋了。聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com