简体   繁体   中英

Sharing connection string between two seperate windows forms application?

I am making a line of windows forms applications. I am building the funcionality of an options menu using the application settings tools to keep persistent data and settings. In addition, all applications will allow the user to connect to a database and query data. I am trying to find out a way to put a databse section in the options to allow the user to test and set database options. When set I want the same settings to show up or sync with another application at runtime or when the next time another app is opened.

So far I have been thinking about using the windows registry, or making a project with application settings and adding it to all applications. I also read about using a machine config file. I am not too sure on what is the best or how this would all work when the applications are deployed.

The sharing of settings and/or values is not limited to just a connection string, but any data that may be useful to keep concurrent with all applications.

You can open config files from any place with the ConfigurationManager. With this you can define a central configuration in a directory known to all your applications. See MSDN .

In this case I use SqlServer express, the best free DataBase. In the App.config add this code

    <connectionStrings>
        <add name="MyConnection" connectionString="User ID=sa;Password=XXXXX;Initial Catalog=DATA_BASE_NAME;Data Source=XXXX\SQLEXPRESS"/>
</connectionStrings>

In a Static Class of your application add this method

public static SqlConnection getConnection()
        {
            string conn = string.Empty;
            conn = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
            SqlConnection aConnection = new SqlConnection(conn);
            return aConnection;
        }

When you have need of db connection you call method in this way

SqlConnection aConnection = getConnection();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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