gpt4 book ai didi

c# - 更改 SqlConnection 字符串并在运行时调用 SqlConnectionStringBuilder

转载 作者:太空宇宙 更新时间:2023-11-03 20:09:03 25 4
gpt4 key购买 nike

我的表单中有这个 SqlConnection,在初始化表单时我调用如下:

 public partial class options : Form
{
SqlConnection conn = new SqlConnection(myConnection.DataSource.ConnectionString);

类看起来是这样的:

public class myConnection
{

internal static class DataSource
{
private static string _ConnectionString;
public static string ConnectionString
{
get
{
if (_ConnectionString == null)
_ConnectionString = FunctionToDynamicallyCreateConnectionstring();
return _ConnectionString;
}
}
private static string FunctionToDynamicallyCreateConnectionstring()
{
SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder();

cb.DataSource = Properties.Settings.Default.sql;
cb.InitialCatalog = Properties.Settings.Default.database;
cb.UserID = Properties.Settings.Default.user;
cb.Password = Properties.Settings.Default.pass;
cb.MultipleActiveResultSets = true;

cb.ConnectTimeout = 20;

return cb.ToString();

}}

在我项目的选项表单中,我在按钮单击时执行此操作,这会更改特定字符串的Settings.Settings值,这些字符串稍后将用于SqlConnectionStringBuilder

Properties.Settings.Default.sql = sql.Text;
Properties.Settings.Default.Save();

Properties.Settings.Default.database = database.Text;
Properties.Settings.Default.Save();

Properties.Settings.Default.user = user.Text;
Properties.Settings.Default.Save();

Properties.Settings.Default.pass = pass.Text;
Properties.Settings.Default.Save();

当我完成更改后,我关闭了表单,并在 Form1 中的 FormClosed 事件中引发了 options 表单,我这样做了

conn = new SqlConnection(myConnection.DataSource.ConnectionString);

我认为它会根据 Properties.Settings.Default.pass 等字符串中的实际值更改 connection string。但事实并非如此。

所以我的问题是,是否有可能以某种方式更改已初始化的 SqlConnection 的字符串?

提前感谢您抽出时间。

最佳答案

没有。您必须关闭 SqlConnection 并打开一个新的。

根据MSDN Docs :

The ConnectionString property can be set only when the connection is closed. Many of the connection string values have corresponding read-only properties. When the connection string is set, these properties are updated, except when an error is detected. In this case, none of the properties are updated. SqlConnection properties return only those settings that are contained in the ConnectionString.

小心这一点,因为它会重置许多连接属性:

Resetting the ConnectionString on a closed connection resets all connection string values (and related properties) including the password. For example, if you set a connection string that includes "Database= AdventureWorks", and then reset the connection string to "Data Source=myserver;Integrated Security=true", the Database property is no longer set to "AdventureWorks".

关于c# - 更改 SqlConnection 字符串并在运行时调用 SqlConnectionStringBuilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21294446/

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