0

I am just doing some research at the moment into this and would like to know if it's possible.

I have an application where someone logs in with a username/ I would like to have a table with all the company id's stored and depending on which one they log in using it will use a connection string from the DB for that company.

I am fully aware of how to do it with the web.config but want to minimise the information kept here because potentially we are talking of around 1,000 connection strings.

2
  • 1
    Can you please explain a little more why you have 1,000 different connection strings? Does each client have its own DB? Commented Nov 18, 2013 at 15:50
  • 1
    Why are there 1,000 different connection strings? Do you really have 1,000 different databases? All you've described is a table of company records, nothing more. Commented Nov 18, 2013 at 15:50

2 Answers 2

2

Sure create a table or modify an existing table.

CREATE TABLE Connection
(
     Id INT IDENTITY NOT NULL PRIMARY KEY
    ,ConnectionString VARCHAR(100) NOT NULL
);

INSERT INTO Connection (ConnectionString)
VALUES ('Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;');

I would advise against storing passwords in the connection string when the contents of the table are unencrypted. Setup a domain account with Sql Server privileges to run your IIS app pool or Windows Service under.

const string Query = "SELECT ConnectionString FROM Connection WHERE Id = @Id";

public string GetConnectionString(int id)
{

    using(var connection = GetConnection())
    using(var command = new SqlCommand(Query, connection))
    {
        command.Parameters.AddWithValue("@Id", id);
        connection.Open();

        using(var reader = command.ExecuteReader())
        {
            if(reader.Read())
            {
                return Convert.ToString(reader["ConnectionString"]);
            }
        }
    }
}

var connectionString = GetConnectionString(1);
using(var connection = new SqlConnection(connectionString))
{
    //logic
}
Sign up to request clarification or add additional context in comments.

Comments

2

Yes, this is possible.

Store the connection strings in your (main?) DB, retrieve them and use them when instantiating new DdConnections.

Most of the classes that inherit from DbConnection (SqlConnection, for example) have a constructor overload that takes a connection string.

3 Comments

In a chicken and egg scenario, you have to be able to connect to the db that contains the connections strings.
@DanBracuk - not really. You have a single connection string in the .config to a central DB that contains all the other ones.
True, but I thought that detail was worth mentioning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.