Rashmi
Rashmi

Reputation: 121

Dynamically create a database connection for SQL Server

Is there a way of inputting username, password & data source name from user instead of hardcoding them?

Right now I have hardcoded in app.config like this

<connectionStrings>
<add name="SQLConnectionString" connectionString="Data Source=db01\instance01;Initial Catalog=testdb; MultipleActiveResultSets=true;User ID=testuser;Password=readonly; Connection Timeout=60;" providerName="System.Data.SqlClient"/>
</connectionStrings>

When I run the console app, I want it to print how to enter the parameters and then accept parameters. How can I do this?

Thanks Rashmi

Upvotes: 0

Views: 2077

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 156988

You can simply create a SqlConnection and set the connection string as first parameter.

string username = Console.ReadLine();

SqlConnection conn = new SqlConnection("User ID=" + username);

Additionally you can take a look at the SqlConnectionStringBuilder that does more for the work for you.

Upvotes: 1

Related Questions