정적 클래스의 asp.net MVC에서 정적 변수 : 액션 홈내가 정적 클래스 데이터가
public static class Data
{
public static SqlConnection connexion;
public static bool Connect()
{
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Initial Catalog"] = "Upload";
builder["Data Source"] = "base";
builder["integrated Security"] = true;
string connexionString = builder.ConnectionString;
connexion = new SqlConnection(connexionString);
try { connexion.Open(); return true; }
catch { return false; }
}
public static void Disconnect()
{
if (connexion != null) connexion.Close();
connexion = null;
}
}
:
public ActionResult Home()
{
Data.Connect();
if (CompteModels.Connected)
{
ArrayList model = new ArrayList();
ClientModels clients = new ClientModels();
model.AddRange(clients.Client_List());
AdminModels admins = new AdminModels();
model.AddRange(admins.Admin_List());
return View(model);
}
else return RedirectToAction("Login", "Account");
}
클라이언트 클래스 :
public List<ClientModels> Client_List()
{
List<ClientModels> l = new List<ClientModels>();
using (Data.connexion)
{
string queryString = @"select Login, Password, Mail, Name, Tentatives from Compte where User_type_id in (select Id from User_type where Fonction = 'Client')";
SqlCommand command = new SqlCommand(queryString, Data.connexion);
try
{
SqlDataReader reader = command.ExecuteReader();
do
{
while (reader.Read())
{
ClientModels admin = new ClientModels { Login = reader.GetString(0), Password = reader.GetString(1), Mail = reader.GetString(2), Name = reader.GetString(3), Tentatives = reader.GetInt32(4) };
l.Add(admin);
}
} while (reader.NextResult());
return l;
}
catch { return null; }
}
을
함수의 경우 AdminList
인 경우 구현은 Client_List
과 같지만 클래스는입니다..
문제는 정적 변수 connexion
에 : 첫 번째 함수에 Client_List
그 값이 정확하고 i는 클라이언트의 목록을 얻을 수 있지만, 정적 클래스의 정적 변수가에도 불구하고 두 번째 기능에 null
되고있다! !
이 변경의 이유는 무엇입니까? 어떻게 해결할 수 있습니까?
에
유사한 새 연결을 만들 수는 IDisposable 인터페이스
변경을 사용하여 접속을 처분 정적 필드에서 열린 SqlConnection'은 여러 가지 이유로 나쁜 생각 일 수 있습니다. 그것이 처음 사용 된 후에 처리되기 때문에 'null'일 가능성이 큽니다. 필요한 때에 새로운'SqlConnection'을 생성하고 즉시 해제하십시오. 무기한으로 SQL 자원을 보류하지 마십시오. – David
@David +1, 아주 나쁜 아이디어. –
'(Data.connexion) 사용하기'- 첫 번째 소비자가 그것을 사용하자마자 연결이 닫히고 처리됩니다. David가 말했듯이 연결을 유지하지 마십시오. 필요할 때 열거 나 작업을 마칠 때 닫고 자신의 연결 "풀"을 구현하지 마십시오. – GalacticCowboy