如何用变量传递 ConnectionString 参数?

How to pass ConnectionString parameters with variables?

我有一个 ConnectionString,我想用 .txt 文件中的值将值(数据源、数据库、用户 ID、密码)传递给它,我需要读取它们,然后将它们传递给 connectionString 但我很困惑我应该怎么做。

在我的程序中,我有一个 Helper Class 到 return connectionString

public static class Helper
{
    public static string ConnectionString(string name)
    {
        return ConfigurationManager.ConnectionStrings[name].ConnectionString;
    }
}

这就是我调用 connectionString 的方式,这样我就可以访问数据库数据

using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.ConnectionString("Hotel")))
{
     connection.Execute($"INSERT INTO dbo.Registos_Cancelados(Nome, Telemovel, Data) VALUES(@Nome, @Telemovel, @Data)", new { Nome = nome, Telemovel = telemovel, Data = data });
}

我有一个包含值的文本文件

"DataSourceName"
"DataBaseName"
"User IDName"
"PasswordName"

我希望它们出现在连接字符串中。

<connectionStrings>
    <add name="Hotel" connectionString="DataSource="DataSourceName";Database="DatabaseName";User Id="UserIdName";Password="PasswordName""
        providerName="System.Data.SqlClient" />
</connectionStrings>

您可以像下面这样格式化您的连接字符串,以便稍后传递必要的值,例如 dbname

<connectionStrings>
    <add name="Hotel" connectionString="DataSource={0};Database={1};User Id={2};Password={3}"
        providerName="System.Data.SqlClient" />
</connectionStrings>

之后,在您的助手 class 中,return 格式化连接字符串以及您从 txt 文件中读取的值。

public static string ConnectionString(string name)
    {
        var dataSourceName = "...";
        var dbName = "...";
        var userId = "...";
        var password = "...";

        var connectionString = ConfigurationManager.ConnectionStrings[name].ConnectionString;
        return string.Format(connectionString, dataSourceName, dbName, userId, password);
    }

您正在使用 SqlClient,因此:您最好的选择是 SqlConnectionStringBuilder:

var cb = new SqlConnectionStringBuilder(theBaseString);
cb.DataSource = dataSourceName;
cb.InitialCatalog = dataBaseName;
cb.UserID = userId;
cb.Password = password;
var connectionString = cb.ConnectionString;

如果您没有模板字符串 (theBaseString),只需使用 new SqlConnectionStringBuilder()

这里使用SqlConnectionStringBuilder的好处是它知道所有关于非平凡值、保留字符等的转义规则