gpt4 book ai didi

.net - 关闭数据库连接

转载 作者:搜寻专家 更新时间:2023-10-30 22:15:19 24 4
gpt4 key购买 nike

要关闭我的数据库,我使用这个:SqlConnection.Close();但是我的应用卡在这个方法中...

每次访问数据库时,我都会这样做:

string cmdSQL = "select min(shortAddress) from FreeShortAddress";

using (SqlCeCommand cmd = new SqlCeCommand(cmdSQL))
{
cmd.Connection = (SqlCeConnection)this.SqlConnection;
var r = cmd.ExecuteScalar();
}

这是正确的方法吗?如何查看哪个连接(在哪个表上)被阻止?

谢谢。

[编辑]你知道强制关闭所有连接而不被卡住的命令吗?

最佳答案

我在打开和关闭连接时使用的一般模式是这样的:(取自 an older answer of mine on a question about the using statement 。)这种模式会在应该关闭连接时自动关闭连接。 (退出using语句时)

using (SqlConnection connection = new SqlConnection(connectionString)) 
{
int employeeID = findEmployeeID();
try
{

connection.Open();
SqlCommand command = new SqlCommand("UpdateEmployeeTable", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));
command.CommandTimeout = 5;

command.ExecuteNonQuery();
}
catch (Exception)
{
/*Handle error*/
}

}

关于.net - 关闭数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14058084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com