在 C# 应用程序中更改 SQL Server 的连接字符串

本文关键字:Server 连接 字符串 SQL 应用程序 | 更新日期: 2023-09-27 18:30:42

我创建了用于显示和呈现从SQLServer到pdf/doc/xls的报告的应用程序。因为我需要在运行时更改连接字符串,所以我要求用户在运行时输入值。因此,经过数小时的搜索数千个网站,我找到了不同的解决方案,但没有一个适合我。

我将连接更改放在我的一种方法中,如下所示。

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings.Remove("MapSoftRPTConnectionString");
config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings("MapSoftRPTConnectionString", Parameters.ConnectionString()));
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");

我有默认字符串,有了它,我的机器上一切正常。当我(作为用户)故意插入错误值时,它仍在工作。因此,它没有考虑我的更改。

这是怎么回事?

编辑:

我不需要将其保存到配置中,但我想要的只是让用户能够在运行时创建报告时更改服务器和帐户。已知实现的过程如下:

// .........
// get parameters from user input and store them in variables
// then change connection string
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["MapSoftRPT.Properties.Settings.MapSoftRPTConnectionString"].ConnectionString = @Parameters.ConnectionString();
config.Save(ConfigurationSaveMode.Modified);
// then start rendering report
this.reportViewer1.Reset();
this.reportViewer1.ProcessingMode = Microsoft.Reporting.WinForms.ProcessingMode.Local;
this.reportViewer1.LocalReport.ReportPath = AppDomain.CurrentDomain.BaseDirectory + "''" + Parameters.getReportRDLCName(repType);
this.reportViewer1.LocalReport.DataSources.Clear();
this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource(Parameters.getReportDataSource(repType), Parameters.getReportDataTable(repType)));
bytes = reportViewer1.LocalReport.Render("PDF"); // and send it to FileStream...

在 C# 应用程序中更改 SQL Server 的连接字符串

我不确定是否有特定原因需要将其保存到 config.connection 字符串中,但如果没有...... 你试过吗,

字符串 Connstr ="数据源 = " + 选定IP + ";初始目录 =" + 数据库名称 + ";用户 ID =" + txt用户名.文本 +";密码 ="+ txtPassword.Text +";

如果需要它是全局的,您可以创建一个公共类。