在代码隐藏文件和 web.config 文件中定义 SqlConnection 有什么区别?

What is the difference between defining SqlConnection in code behind file and in web.config file?

代码隐藏中的 SqlConnectionweb.config 中的连接字符串有什么区别?

代码隐藏:

Dim con As SqlConnection = New SqlConnection("Initial Catalog=Election;Data Source=xxx;User ID=xxx;Password=xxx;Persist Security Info=False; Connect Timeout=60")

web.config:

<connectionStrings>
    <add name="conn" 
         connectionString="Initial Catalog=Election;Data Source=xxx;User ID=xxx;Password=xxx;Persist Security Info=False; Connect Timeout=60;Pooling=False" />
</connectionStrings>

连接字符串是包含有关如何连接到数据库的信息的字符串。 SqlConnection 对象是一个实际包含数据库连接并用于针对它执行语句的对象。

您代码中的SqlConnection是您需要在运行时连接到数据库的内容。但是,以这种方式初始化 SqlConnection 将意味着您的应用程序只能以这种方式连接到 SQL 数据库。如果密码更改,或者应用程序需要不同的连接,则必须重写和重新编译应用程序。

配置文件中的连接字符串是一种无需重新编译应用程序即可更改SQL连接字符串的机制。

Dim con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("conn"))

据我所知,

What is the difference between SqlConnection in code behind and connection string in the web config?

当前的行为或工作方式没有区别,您可以将连接字符串放在代码本身或web.config文件中!

Connection string in Code itself:

如果您将连接字符串放在代码本身中,例如:

Dim con As SqlConnection = New SqlConnection("Initial Catalog=Election;Data Source=xxx;User ID=xxx;Password=xxx;Persist Security Info=False; Connect Timeout=60")

如果更改密码或有时您想更改 Connection Timeout = 90 在这种情况下,您必须构建一个应用程序并发布以获取更新的更改。

Connection string in web.config file:

<connectionStrings>
    <add name="constr" 
         connectionString="Initial Catalog=Election;Data Source=xxx;User ID=xxx;Password=xxx;Persist Security Info=False; Connect Timeout=60;Pooling=False" />
</connectionStrings>

在后面的代码中访问:

string ConStr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
Dim con As SqlConnection = New SqlConnection(ConStr)

如果密码更改或连接字符串有任何修改,只需更改 web.config 文件,因为我们正在从 web.config 动态读取连接字符串,所以每次您都会得到该字符串那是在 web.config

两者之间没有主要区别。两者是如何向对象SQLCommand 提供连接字符串的两种不同机制。

根据需求,在web.config中使用和更改为生产服务器而不停机是更可行的。

几次我们知道我们需要更改服务器名称、数据库名称、密码、超时等。当它在后面的代码中定义时,您需要首先重新编译并将其发布到服务器,这是一个时间和资源消耗。

当我们需要动态提供连接时,我们通常在代码后面使用连接字符串,例如从下拉列表中选择或希望根据日期进行更改等。虽然这也可以在 web.config 中完成定义不同的连接字符串并根据代码后面的条件决定我们需要使用哪个。