为什么SqlConnection会忘记数据库类型

发布于 2024-09-28 16:14:58 字数 731 浏览 0 评论 0原文

我最近发布了一个关于 SqlConnection 在“ChangeDatabase”范围结束时丢失其数据库信息的问题(当我认为该问题与实际问题无关时,立即删除)。示例:

    //Other code...
    dbConn = new SqlConnection(dbConnBuilder.ConnectionString);
    dbConn.Open();
    dbConn.ChangeDatabase(currentDatabase);
    dbConn.Close();
}

我的问题:

  1. 当您只拥有给定类型的一个连接时,保留 SqlConnection 对象并在需要时打开和关闭它是否被视为不好的做法?
  2. 为什么在 ChangeDatabase(方法而不是变量)“超出范围”之后dbConn.Database记住currentDatabase '? (哎呀,我不知道像 ChangeDatabase 这样的方法可以了解范围)。

我的连接字符串是:

Data Source=server.name.com;Persist Security Info=True;User ID=username;Password=password

谢谢大家,请告诉我是否可以为您提供更多信息,仍在学习使用 SO

I recently posted (and promptly deleted, when I decided the question was irrelevant to the actual problem) a question about SqlConnection losing its Database information when the scope of "ChangeDatabase" ends. Example:

    //Other code...
    dbConn = new SqlConnection(dbConnBuilder.ConnectionString);
    dbConn.Open();
    dbConn.ChangeDatabase(currentDatabase);
    dbConn.Close();
}

My questions:

  1. Is it considered bad practice to hold onto a SqlConnection object and open and close it whenever you need it when you'll only ever have ONE connection of a given type?
  2. Why does dbConn.Database not remember currentDatabase after ChangeDatabase (a method not a variable) 'Goes out of scope'? (Heck, I didn't know methods like ChangeDatabase could know about scope).

My connection string was:

Data Source=server.name.com;Persist Security Info=True;User ID=username;Password=password

Thanks guys, let me know if I can give you more information, still learning to use S.O.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

王权女流氓 2024-10-05 16:14:58

调用 Close() 会完全销毁该对象,因此您之后不应读取其任何属性。

事实上,甚至应该有一个“after”,因为您不应该调用Close()。相反,在 using 块中实例化连接,以便它调用 Dispose(),这与 Close() 执行相同的操作,但无论您如何离开街区,都保证会这样做。

Calling Close() completely destroys the object, so you should not be reading any of its properties after.

In fact, there should even be an "after" because you shouldn't be calling Close(). Instead, instantiate the connection in a using block, so that it'll call Dispose(), which does the same thing as Close(), but is guaranteed to do so no matter how you leave the block.

未央 2024-10-05 16:14:58

因此,只需确保每次需要执行语句时都调用changedatabase:-)

So just make sure to call changedatabase every time you need to execute a statement :-)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文