【发布时间】:2013-06-04 14:29:45
【问题描述】:
我有一个静态类数据:
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相同,但在类Admin中。
问题出在静态变量connexion 中:在第一个函数Client_List 中,它的值是正确的,我得到了客户列表,但在第二个函数中它变成了null,尽管它是一个静态变量在静态类中!!!
这个改动的原因是什么?我该如何解决?
【问题讨论】:
-
尝试在静态字段中打开
SqlConnection可能是一个坏主意,原因有很多。很可能是null,因为它在第一次使用后就被丢弃了。只需在需要时创建一个新的SqlConnection,然后立即发布。不要试图无限期地持有 SQL 资源。 -
@David +1,一个非常非常糟糕的主意。
-
using (Data.connexion)- 一旦你的第一个消费者使用它,连接就会关闭并被释放。正如大卫所说,不要保留连接 - 在需要时打开它,完成后关闭它,不要尝试实现自己的连接“池”。 -
这个问题需要一个更好的标题。
标签: c# asp.net .net asp.net-mvc razor