建立ConnectionTestInfo類
using System.Data.SqlClient;
using System.Data;
public class ConnectionTestInfo
{
private static SqlConnection mySqlConnection; //mySqlConnection is a SqlConnection object
private static string ConnectionString = "";
private static bool IsCanConnectioned = false;
/// <summary>
/// 測試連接資料庫是否成功
/// </summary>
/// <returns></returns>
public static bool ConnectionTest()
{
//擷取資料庫連接字串
ConnectionString = ConnectionInfo.ConnectionString();
//建立連線物件
mySqlConnection = new SqlConnection(ConnectionString);
//ConnectionTimeout 在.net 1.x 可以設定 在.net 2.0後是唯讀屬性,則需要在連接字串設定
//如:server=.;uid=sa;pwd=;database=PMIS;Integrated Security=SSPI; Connection Timeout=30
//mySqlConnection.ConnectionTimeout = 1;//設定連線逾時的時間
try
{
//Open DataBase
//開啟資料庫
mySqlConnection.Open();
IsCanConnectioned = true;
}
catch
{
//Can not Open DataBase
//開啟不成功 則串連不成功
IsCanConnectioned = false;
}
finally
{
//Close DataBase
//關閉資料庫連接
mySqlConnection.Close();
}
//mySqlConnection is a SqlConnection object
if (mySqlConnection.State == ConnectionState.Closed || mySqlConnection.State == ConnectionState.Broken)
{
//Connection is not available
return IsCanConnectioned;
}
else
{
//Connection is available
return IsCanConnectioned;
}
}
}
其中資料庫字串調用了類ConnectionInfo的方法ConnectionString
public class ConnectionInfo
{
public ConnectionInfo() { }
/// <summary>
/// 從設定檔中讀取資料庫聯結字串
/// </summary>
/// <returns></returns>
public static string ConnectionString()
{
return (ConfigurationSettings.AppSettings["ConnectionString"]);
}
}
解決ASP.NET Web Applicatio逾時時間已到.在操作完成之前逾時時間已過或伺服器未響應
“逾時時間已到。在操作完成之前逾時時間已過或伺服器未響應”
初步分析原因為對MSSQL操作時連線逾時,知道這事,以前沒留意,大概是在設定檔中設定串連時限,在網上找了下解決方案,大多說在資料庫連接字串裡解決
SqlConnection con = new SqlConnection("server=.;database=myDB;uid=sa;pwd=password;")改為:
SqlConnection con = new SqlConnection("server=.;database=myDB;uid=sa;pwd=password;Connect Timeout=500")似乎沒效果。依然運行30秒即報逾時!
突然感覺似乎應該可以在串連資料庫代碼中指明,式了下con的屬性,有個ConnectionTimeout,
SqlConnection con = new SqlConnection("server=.;database=myDB;uid=sa;pwd=;");
con.ConnectionTimeout = 180;//報錯,屬性ConnectionTimeout 為唯讀!嘗試失敗,再接著看command對象屬性,發現其也有類似屬性!CommandTimeout設定一下:
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 180;再運行,即解決,這裡設定的時間的180秒,即三分鐘!可根據需要設定,如果過長,也可以設定為0,當此屬性設定為0時表示不限制時間。此屬性值應該慎用。還需要在Web.config設定檔中設定http請求運行時限間
<system.web>
<httpRuntime maxRequestLength="102400" executionTimeout="720" />
</system.web>