Click here to Skip to main content
15,890,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to provide connection string Dynamically.
I have connection string name but I want to set Database name in appsetting.json file at run time.

What I have tried:

string connetionString;
                   SqlConnection cnn;
                   connetionString = @"Data Source=.;Initial Catalog=Name;Integrated Security=True";
                   cnn = new SqlConnection(connetionString);
                   cnn.Open();

                   SqlCommand command;
                   SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
                   SqlDataReader sqlDataReader;
                   string sql, Output = "";

                   sql = "select * from table";
                   command = new SqlCommand(sql, cnn);
Posted
Updated 19-Jun-19 21:59pm

1 solution

In the settings file use a token for the database name

server=localhost; database=[db]; uid=sa; pwd=


then in your code read the connection string from the config file and do a string replace;

connetionString = connetionString.Replace("[db]", "YourDatabaseNameHere");
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900