【问题标题】:ConnectionString with external file for SqlConnectionConnectionString 与 SqlConnection 的外部文件
【发布时间】:2017-06-15 13:51:14
【问题描述】:

VisualStudio 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;

当然不行。

对替代解决方案有什么想法吗?

【问题讨论】:

  • 我会创建一个登录页面,并使用参数(例如<add name="DbConn" connectionString=" Data Source=.\\SQLEXPRESS;User Id={0};Password={1};"/> )从.Config 文件中的连接字符串中读取用户名和密码,然后当您读取要添加的配置文件时读取 .config 文件时的 2 个额外参数..
  • @MethodMan 是的,我认为这是最好的选择。并研究了您的答案,我设法找到了妥协!下面看看我的回答。所以非常感谢你的提示。 ;)
  • 不是问题,只是很高兴为您指明正确的方向并很高兴您听取了建议

标签: c# connection-string sqlconnection udl2


【解决方案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中:

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>

这对我有用!

【讨论】:

  • 显然,您可以手动直接从 MyProjectName.exe.config 文件更改 connectionString,而无需使用 FormConn .
猜你喜欢
  • 2015-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-19
  • 1970-01-01
相关资源
最近更新 更多