简体   繁体   中英

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

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.

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