Pass connection string to dataset via code

1

How to pass the string connection to the dataset via code? because the application I'm developing can not contain app.config .

    
asked by anonymous 09.01.2015 / 17:20

2 answers

1

There is no secret:

var connectionString = "Data Source=MSSQL;Initial Catalog=SeuBanco; Integrated Security=true;";
using (var connection = new SqlConnection()) {
    connection.ConnectionString = connectionString;
    connection.Open();
    Console.WriteLine("Estado: {0}", connection.State);
    Console.WriteLine("ConnectionString: {0}", connection.ConnectionString);
}

Other possibilities of strings (ideally not having loose passwords like this):

Server=localhost;Database=meuDB;User Id=meuUsername;Password=minhaPassword;

Server=10.0.0.1,1433;Database=meuDB;Trusted_Connection=True;
    
09.01.2015 / 18:09
1

Be careful not to put the connection string in the code. Evaluate where your component will be used (type and application and find a correct method to store the configuration string.

If your component is going to be used in a web application, you can use web.config, if the app.config is desktop, if you do not want either, use an external txt to the application because maintenance is usually trivial to do and changing a connection string should not require recompiling the code.

You can either isolate this configuration logic in a Factory or leave the top layer (if you use layered architecture) to properly instantiate the repository. Passing these settings to the constructor.

    
12.01.2015 / 14:30