ConnectionString与SqlConnection

时间:2017-06-15 13:51:15

标签: c# connection-string sqlconnection udl2

Visual Studio 2017上的C#。Windows窗体应用程序。

大家好。我在网上看过,无法使用 .udl 文件为 SqlConnection 编写 ConnectionString 。今天是真的吗?并且,如果是,在 SqlConnetion 中有另一种方法可以将外部文件用于 ConnectionString 吗?

我必须在具有不同连接字符串的5台PC中运行项目,例如:

  

PC1)数据源= PCNAME \ SQLEXPRESS;初始目录= DBNEW;用户ID = sa;密码= 123;

     

PC2)数据源= SERVER \ SQLEXPRESS;初始目录= DB;用户ID = sa;密码= 999;

     

[...]

目前我在项目中使用了一个字符串

string connSQL = "Data Source=.\\SQLEXPRESS;Initial Catalog=DBNEW;Persist Security Info=True;User ID=sa;Password=123;";

我需要为五台电脑改变五次'不同的联系。

我还是尝试连接.udl文件

string connSQL = "Data Source=.\\SQLEXPRESS;AttachDbFile=C:\\connstring.udl";

包含此

[oledb]
; Everything after this line is an OLE DB initstring
Data Source=PCNAME\SQLEXPRESS;Initial Catalog=DBNEW;Persist Security Info=True;User ID=sa;Password=123;

但当然它不起作用。

有关替代解决方案的任何想法吗?

1 个答案:

答案 0 :(得分:1)

最后我找到了解决方案。还要感谢 MethodMan 的评论我后来意识到你可以使用外部文件编译 connectionString ,即 MyProjectName.exe.config ,它保存在与软件exe相同的目录中,并且具有与 App.config 相同的功能和设置。

所以我做的是创建一个新的 FormConn ,您手动输入 connectionString 的数据,在 MyProjectName.exe.config 中覆盖它们并将此文件链接到 Form1 以进行SQL数据库管理。代码下方。

Form1.cs

using System.Configuration;

public Form1()
{
    //Check if a connectionString already exists
    //To the first slot there is a system configuration so 1 = no custom connectionString
    if (ConfigurationManager.ConnectionStrings.Count == 1)
        {
            FormConn frmConn = new FormConn();
            frmConn.ShowDialog();
            try
            {
                //Restart Form1 in the case connectionString has changed
                Application.Restart();
            }
            catch(Exception ex)
            {
                 MessageBox.Show(ex.Message);
            }
        }
        //Associates the custom connectionString to the string I will use in the code for operations that are connected to the DB.
        StringSQL = ConfigurationManager.ConnectionStrings[1].ConnectionString;
}

FormConn.cs

FormConn (Design)

using System.Configuration;
using System.Reflections;

string appPath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        string appName = Environment.GetCommandLineArgs()[0];
        string configFile = System.IO.Path.Combine(appPath, appName + ".config");
        ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
        configFileMap.ExeConfigFilename = configFile;
        System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
        var sezione = (ConnectionStringsSection)config.GetSection("connectionStrings");<br>sezione.ConnectionStrings["MyProjectName.Properties.Settings.MyDataSetConnectionString"].ConnectionString = "Data Source=" + txtDataSource.Text + ";Initial Catalog=" + txtInitialCatalog.Text + ";Persist Security Info=True;User ID=" + txtUserID.Text + ";Password=" + txtPassword.Text + ";";
        config.Save();
        ConfigurationManager.RefreshSection("connectionStrings");
        this.Close();

这就是我在 MyProjectName.exe.config 中的内容:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
<connectionStrings>
    <add name="MyProjectName.Properties.Settings.MyDataSetConnectionString"
        connectionString="Data Source=MyPcName\SQLEXPRESS;Initial Catalog=DB-1;Persist Security Info=True;User ID=sa;Password=123psw321"
        providerName="System.Data.SqlClient" />
</connectionStrings>
<startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>

这对我有用!