Pass connection string to dataset via code

Asked

Viewed 908 times

1

How to pass the string connecting to the dataset via code? because the application I am developing cannot contain the app.config.

  • And what do you want to know? Have some code to demonstrate what you want?

  • When creating a dataset, visual studio already automatically includes an app.config file with the database connection. I would like to pass the connection string via code, so you don’t need this file.

  • Okay, but you want to do like, in that code. You can put anything you turn?

2 answers

1


It’s 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);
}

I put in the Github for future reference.

Other possibilities of strings (ideal is not to have loose passwords like this):

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

Server=10.0.0.1,1433;Database=meuDB;Trusted_Connection=True;

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 it’s desktop app.config, if you don’t want either, use an external txt to the application because maintenance is usually trivial to do and change a connection string should not require recompiling the code.

You can isolate this configuration logic in a Factory or let the top layer (if you use layered architecture) correctly instantiate the repository. Passing these settings to the builder.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.