【发布时间】:2012-05-26 22:05:02
【问题描述】:
我正在使用下面的代码,我想要做的是在用户登录期间使用相同的连接。现在我对使用的理解是它处理连接,但我真正想要的是要做的是当用户登录时,创建一个连接并让他们使用该特定连接。
下面是我知道的用于在 C# 中设置连接的代码,我会将 [ThreadStatic] 属性应用于public static MySqlConnection ATCrawlerConnection,但是您如何在 aspx 中完成类似的功能,基本上为每个用户创建一个连接,然后访问并限制该用户的连接?
在 C# 中我会使用这个:
MySQLProcessing.MySQLStatic.ATCrawlerConnection MySQLProcessing.MySQLStatic.OpenCon("10.2", 3306, "user", "pw");
公共静态 MySqlConnection ATCrawlerConnection { 获取;放; }
public static MySqlConnection OpenCon(string ServerAddress, int PortAddress, string UserID, string Password)
{
MySqlConnection masterOpenCON = new MySqlConnection("server=" + ServerAddress + ";Port=" + PortAddress + ";UID=" + UserID + ";PASSWORD=" + Password);// + ";connectiontimeout=" + ConnectionTimeOut + " ;");
masterOpenCON.Open();
返回masterOpenCON;
}
public static DataTable StoreProcedureDTTable(string mysqlQuery, string[] CommandArgs, string queryName)
{
lock (_object)
{
using (MySqlConnection cn = new MySqlConnection(applicationStringClass.AuthMySQLConnector))
{
DataTable DTTableTable = new DataTable();
try
{
MySqlCommand MySQLCommandFunc = new MySqlCommand(mysqlQuery);
MySQLCommandFunc.Connection = cn;
MySQLCommandFunc.CommandType = CommandType.StoredProcedure;
foreach (string args in CommandArgs)
{
string[] splitArgs = args.Split('|');
MySQLCommandFunc.Parameters.AddWithValue(splitArgs[0], splitArgs[1]);
}
MySqlDataAdapter DataDTTables = new MySqlDataAdapter(MySQLCommandFunc);
DataTable DataDTTablesDT = new DataTable();
DataDTTables.SelectCommand.CommandTimeout = 240000;
DataDTTables.Fill(DataDTTablesDT);
DTTableTable = DataDTTablesDT;
}
catch (Exception ex)
{
}
return DTTableTable;
}
}
}
【问题讨论】:
-
Static 将为每个用户使用相同的连接,系统中有一个静态对象的单个实例。但是为什么你想要这个要求,如果连接没有返回到连接池或事务锁,如果你有高并发性,维护单个连接可能会导致问题
-
你的概念违背了微软关于如何使用连接和使用连接池的建议。您可以阅读更多here:“我们强烈建议您在使用完毕后始终关闭连接,以便将连接返回到池中”
-
@Mike 你为什么要这样做?