gpt4 book ai didi

c# - 在我的代码中使用 "using"的正确方法

转载 作者:行者123 更新时间:2023-12-02 04:44:08 25 4
gpt4 key购买 nike

我只想知道在我的 CRUDStudentTable() 中使用“using”是否正确。

private string Query;
public string message;

public CRUD(string myQuery)
{
Query = myQuery;
}

public void CRUDStudentTable()
{
using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\Microsoft User\Desktop\Student.accdb"))
{
try
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(Query, conn))
{
cmd.ExecuteNonQuery();
}
}
catch (Exception exception)
{
message = exception.Message;
}
finally
{
conn.Close();
}
}
}

public string HasError()
{
if (string.IsNullOrEmpty(message))
{
message = "Successful";
return message;
}
else
{
return message;
}
}

如果这不对,请给我一个如何正确执行此操作的建议。谢谢。

我在这里包含了另一个方法,只要它不为 null 就返回“消息”。

最佳答案

这是一种“腰带和吊带”方法:您应该使用 usingfinally,但不能同时使用两者。

using block 保证关闭所有代码路径中的连接,包括有异常的代码路径。因此你可以重写代码如下:

public void CRUDStudentTable()
{
using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\Microsoft User\Desktop\Student.accdb"))
{
try
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(Query, conn))
{
cmd.ExecuteNonQuery();
}
}
catch (Exception exception)
{
message = exception.Message;
// Consider re-throwing the exception here
// to let callers know what happened.
// Silently harvesting the message and continuing
// is not a good practice of handling exceptions.
}
}
}

关于c# - 在我的代码中使用 "using"的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20170624/

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