SQL连接/命令适当的管理(避免表锁)
本文关键字:管理 连接 命令 SQL | 更新日期: 2023-09-27 18:08:16
我正在为一个。net项目建立一个连接工厂,我想问一下最好的方法是什么。我有一个问题,以前的Log类不能正确地编写日志,因为表锁(或他们说),所以我的任务是建立一个新的数据层,(希望)解决这个问题以及其他一些小问题。
现在,代码:
public sealed class ConnectionFactory
{
//Will be SQL only
private static SqlConnection sqlConnection = null;
private static string connectionString = ConfigurationManager.ConnectionStrings["Development"].ConnectionString;
public static SqlConnection GetConnection()
{
if(sqlConnection == null)
{
sqlConnection = new SqlConnection();
sqlConnection.Open();
}
return sqlConnection;
}
}
我将使用大多数过程,但可能有一个或另一个奇怪的请求,如果需要,我们将键入查询,所以我认为我必须以某种方式添加SqlCommand:
private static SqlCommand sqlCommand = null;
public static SqlCommand GetCommand()
{
//Check if sqlConnection is not null (omitted)
if(sqlCommand == null)
{
sqlCommand = sqlConnection.CreateCommand();
}
return sqlCommand;
}
但是,这个命令应该是静态的吗?还是应该在每次执行新查询时创建一个新查询?考虑到大多数情况下避免锁,它是由多个命令或多个连接引起的吗?我该如何避免和正确处理这种情况?
我相信"nolock"在这种情况下会起作用…
FROM [table] with (nolock)
直接查询