Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the Web.Config to set up my SQL database connection string?

Tags:

Can anyone help me out please? I'm confused.

I want to set up my connection string so I can just call it from my Web.Config file.

I need a way to call it from my code, please make a little example. :(

I also need help on setting up the Web.Config file.

I don't know what properties to use. Here's a screenshot of what my credentials are. I have no password set up for Windows. I'm really lost here.

alt text

like image 218
Sergio Tapia Avatar asked Aug 31 '09 01:08

Sergio Tapia


People also ask

Where do I put connection string in web config?

After opening the web. config file in application, add sample db connection in connectionStrings section like this: <connectionStrings>

How can I set an SQL Server connection string?

You can either use the new operator to make that directly. For example: SqlConnection conn = new SqlConnection( new SqlConnectionStringBuilder () { DataSource = "ServerName", InitialCatalog = "DatabaseName", UserID = "UserName", Password = "UserPassword" }. ConnectionString );

What is SQL connection string in web config?

and read from it like this: string strcon = ConfigurationManager. ConnectionStrings["Dbconnection"]. ConnectionString; SqlConnection DbConnection = new SqlConnection(strcon);


1 Answers

Here's a great overview on MSDN that covers how to do this.

In your web.config, add a connection string entry:

<connectionStrings>   <add      name="MyConnectionString"      connectionString="Data Source=sergio-desktop\sqlexpress;Initial      Catalog=MyDatabase;User ID=userName;Password=password"     providerName="System.Data.SqlClient"   /> </connectionStrings> 

Let's break down the component parts here:

Data Source is your server. In your case, a named SQL instance on sergio-desktop.

Initial Catalog is the default database queries should be executed against. For normal uses, this will be the database name.

For the authentication, we have a few options.

User ID and Password means using SQL credentials, not Windows, but still very simple - just go into your Security section of your SQL Server and create a new Login. Give it a username and password, and give it rights to your database. All the basic dialogs are very self-explanatory.

You can also use integrated security, which means your .NET application will try to connect to SQL using the credentials of the worker process. Check here for more info on that.

Finally, in code, you can get to your connection string by using:

ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString 
like image 99
Rex M Avatar answered Oct 02 '22 09:10

Rex M