pss1337
pss1337

Reputation: 21

Creating an SQL Server connection string without importing a datasource in C#

I am going off of this tutorial: http://www.dotnetperls.com/sqlclient . Instead of adding a data source and a having visual studio compile my connecting string - I want to do it myself. The reason being is that the database will not always be the same and I want this application to be able to use different databases depending on which I point it to.

So how can I manually create the connection string? I am using SQL Server 2005.

Upvotes: 2

Views: 3547

Answers (3)

Ashu
Ashu

Reputation: 51

for SQL Server format of the connection string is

"Data Source = server_address; Initial Catalog = database_name; User ID = UserId; Password = **;"

save this connection string in a string variable and use with connection object.

either way you can add in web.config file.

<ConnectionString>
<add name = "name_of_connecctionString" ConnectionString = "Data Source = server_address;       Initial Catalog = database_name; User ID = UserId; Password = ****;" ProviderName = "system.Data.SqlClient"/>
</ConnectionString>

you can change the provider as needed by you.

then in code behind file access this particular connection string using configuration manager.

Upvotes: 0

Justin Niessner
Justin Niessner

Reputation: 245429

Step 1: Go to connectionstrings.com and find the proper format for your database.

Step 2: Plug in the appropriate values to the connection string.

Step 3: Pass that string to the constructor of SqlConnection.

I would also suggest storing your connection string in your app.config/web.config file. You can then modify them easily if needed. The proper format can be found at MSDN - connectionStrings element. You then change your code to:

 SqlConnection sqlConn = new SqlConnection(
     ConfigurationManager.ConnectionStrings["ConnStringName"].ConnectionString);

Upvotes: 2

Miserable Variable
Miserable Variable

Reputation: 28752

I don't see where the connection string is "compiled".

In the code

SqlConnection con = new SqlConnection(
    ConsoleApplication1.Properties.Settings.Default.masterConnectionString)

ConsoleApplication1.Properties.Settings.Default.masterConnectionString is a field and it can be replaced with any other appropriate string.

Upvotes: 0

Related Questions