Click to See Complete Forum and Search --> : ASP.NET Connection to MS SQL Server 2005 Express


cancer10
12-12-2008, 04:17 AM
Hi Ppl,


I come from a PHP programming background, I also know classic asp 3 very well. Now, I wanna learn ASP.net, Last night I was going through an ASP.net Ebook, But the connection string given in that book had many lines of code and confusing too.

In PHP or classic asp, we had 1 or just 2 line of code for connecting to the DB (in VB and C#).

Can someone please tell me a connection code with a minimal line of code?

Also, Since I am from a PHP background, Plz suggest me which language should I use for ASP.net (VB or C#)?


Thanx

ryanbutler
12-12-2008, 09:29 AM
What I would do, is create an application in IIS and then create a web.config file that lists your connection string information in one place. You can Google to find an example of a connection string in ASP.NET through a web.config file. Then in the code behind file, all you need to do is:

protected Page_Load(object s, eventargs e){

using(SqlConnection sqlConn=new SqlConnection(ConfigurationManager.AppSettings["MyConnectionString"].ConnectionString))

}

And yes, I would definitely go C#

debiguana
12-13-2008, 12:11 AM
the minimal code to do so is (C# code here - VB code similar):
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ConnectionString);
conn.Open();

The first line imports the appropriate libraries, the second instantiates the object, and the third opens the connection.

In practical reality, you will want to wrap the Opening, executing of queries, and Closing of the database in a try/catch/finally block.

You definitely want to use the web.config to store the connection string. Changing the connectionstring on 200 files is a royal pain (and yes, I've had to do that cleaning up after a programmer).