简体   繁体   English

如何在运行时以编程方式从本地数据库获取连接字符串? c# winforms

[英]how to programmatically get connection string from local database at run time? c# winforms

I have created a local DB programmatically using Winforms (c#) and added tables, stored procedures to it, and stored on the user's preferable location.我已经使用 Winforms (c#) 以编程方式创建了一个本地数据库,并向其中添加了表、存储过程,并存储在用户的首选位置。 Now, all I want is to make my Winforms app access it using without opening visual studio or SSMS to get the connection string for that database.现在,我只想让我的 Winforms 应用程序在不打开 Visual Studio 或 SSMS 的情况下使用它来获取该数据库的连接字符串。

My try: I did open the visual studio to get the database's connection string to add it to the WinForms app's connection string and I want to make transactions with it.我的尝试:我确实打开了 Visual Studio 以获取数据库的连接字符串以将其添加到 WinForms 应用程序的连接字符串,并且我想使用它进行交易。

Is there any way to programmatically retrieve the connection string of the user-selected database from the Winforms application?有没有办法以编程方式从 Winforms 应用程序中检索用户选择的数据库的连接字符串?

Like,喜欢,

  1. User chooses the location of already created localdatabase.mdf from his WinForms app.用户从他的 WinForms 应用程序中选择已创建的 localdatabase.mdf 的位置。
  2. The application retrieves the connection string so that he can use it to connect to the database.应用程序检索连接字符串,以便他可以使用它连接到数据库。

The retrieval can be of parts like only retrieving the Data Source for the database.检索可以是仅检索数据库的Data Source等部分。 I can manage to build the connection string with it.我可以设法用它建立连接字符串。 Like using the name of the file for Initial Catalog and adding Integrated security using strings.就像使用Initial Catalog的文件名和使用字符串添加Integrated security一样。

Any ideas regarding this will really help.任何关于此的想法都会有帮助。 Thank guys.谢谢大家。

You can get and edit the connection string using SqlConnectionStringBuilder Class.您可以使用SqlConnectionStringBuilder Class 获取和编辑连接字符串。

Here the connection string is local to the method but any place in scope of the method below.这里的连接字符串是方法的本地,但在下面方法的 scope 中的任何位置。

public static void ChangeConnectionStringFromExisting()
{

    var connectionString = "Server=localhost;Integrated security=SSPI;database=master";

    var builder = new SqlConnectionStringBuilder(connectionString);

    builder.DataSource = "(LocalDB)\\MSSQLLocalDB";
    builder.InitialCatalog = "MyAppDatabase.mdf";

    connectionString = builder.ConnectionString;

    using (var cn = new SqlConnection(connectionString))
    {
        // . . .
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM