Waqas Ali
Waqas Ali

Reputation: 53

Create Dynamic Connection in asp.net c# on run time

I want to create of dynamic connection string of dynamic database.I have login page in asp.net c#.Where user can enter the database name and database user/password.I want user can login according to db name and db user and password.I do not want to create dynamic connection in web.config file because when i dynamically change the web.config file application again will be restart.Is there any way to do this.I have multiple per user of different database and different user name and different password.How can i acheive this on run time.Different database uses same application.I want every user can connect according to his database.

string Constring = generateConnectiontring();
    public string generateConnectiontring()
            {
                var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
                var stringChars = new char[8];
                var random = new Random();

                for (int i = 0; i < stringChars.Length; i++)
                {
                    stringChars[i] = chars[random.Next(chars.Length)];
                }

                var finalString = new String(stringChars);
                return finalString;
            }

and now I want to create a dynamic connection with dynamic database name and password.Same to like php.I want to define database and credentials in page.

Upvotes: 0

Views: 1216

Answers (1)

bluetoft
bluetoft

Reputation: 5443

You can use a SqlConnection

private static void CreateCommand(string queryString,string connectionString)
{
    using (SqlConnection connection = new SqlConnection(
           connectionString))
    {
       SqlCommand command = new SqlCommand(queryString, connection);
       command.Connection.Open();
       command.ExecuteNonQuery();
    }
}

Upvotes: 1

Related Questions