Wednesday, February 11, 2009

Code 4 Jay: How to set MS SQL connection in Web.config?

In order to get this done, of course you need to have your DBMS and IDE ready, in this case will be MS SQL 2005 and VS 2005 respectively.

First of all, launch your VS 2005 and create a website if you didn't do so earlier. You shall see a file called Web.config created along with your website. Open the file and scroll it downwards the end where you see the line . Right before this line, add in the code below:

<appsettings>
<add key="ConnectionString" value="server = COMPUTER_NAME\SERVER_INSTANCE_NAME;database=DATABASE_NAME;uid=USER_ID;password=PASSWORD">
</add>
</appsettings>

Kindly note that you should have your own value of COMPUTER_NAME\SERVER_INSTANCE_NAME, if you are not sure you can obtain such information from the MS SQL. DATABASE_NAME will be the DB that you are trying to connect, USER_ID and PASSWORD will be the user ID and password that you use to connect MS SQL.

By doing so, you should now have a key called "ConnectionString" which you can use in the project as server connection reference. Next go to your code behind (aspx.vb) by clicking the "+" sign at your aspx file. In code behind you shall see lines like:

Partial Class demo
Inherits System.Web.UI.Page
End Class

Right before the "Partial Class demo", add lines below so that you can utilize all SQL related codes:

Imports System.Data.SqlClient
Imports System.Data

After that, add lines below after "Inherits System.Web.UI.Page":

Dim strConn As String = System.Configuration.ConfigurationSettings.AppSettings("ConnectionString")
Dim conn As SqlConnection = New SqlConnection(strConn)

By doing so, you can now use "conn" as your SQL connection whenever you try to query the DB. As a recap, your final outline of the codes should look something like this:

Imports System.Data.SqlClient
Imports System.Data

Partial Class demo
Inherits System.Web.UI.Page

Dim strConn As String = System.Configuration.ConfigurationSettings.AppSettings("ConnectionString")
Dim conn As SqlConnection = New SqlConnection(strConn)

End Class

Enjoy the fun!

No comments:

Post a Comment