0

I am making C# windows form application - is connected to database, so I need connection with it.

The "problem" is that my application should work on any PC.

But, as we know, every PC has different SQL connection string. It would be a little bit unpractical to change connection string in code every time when someone runs application.

So, my question is, is there a way to avoid this?

7
  • 6
    "Every PC has different connection string"? Why? Commented Apr 17, 2016 at 19:00
  • Are you also installing the database as part of your application? If so you can just use "localhost" to reference the database. Commented Apr 17, 2016 at 19:03
  • @Jon Because it has different SQL server name? Commented Apr 17, 2016 at 19:04
  • 3
    Usually connectionstrings are stored in the app.config file as a plain text. It is a job of your setup app to change the connectionstring to match the server and other parts of this connectionstring as required by your customer environment Commented Apr 17, 2016 at 19:06
  • 6
    Your application is connecting to a server/database stored locally on the computer running the application? Use "(local)" as your server name. Also have a look at emoreau.com/Entries/Articles/2009/05/… to see how to store your connection string in a config file Commented Apr 17, 2016 at 19:06

2 Answers 2

2

Usually, your connection strings goes in a xml .config file :

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <add name="Test" connectionString="Data Source=SERVER;Initial Catalog=DATABASE;User Id=USER;Passwor=PASSWORD" providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

And you get them using the ConfigurationManager :

var connectionString = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;

You will still need to update the .config file on each PC, but not recompile the source.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this is exactly what I needed :)
0

This is a example to connect to the same database from all PC

    //Geting Connection to database
    static SqlConnection GetConnection()
    {
        return new SqlConnection(@"Data Source=.\SQLEXPRESS; Initial Catalog=Northwind; Integrated Security=SSPI");
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.