Hosting Articles

Database Connectivity in ASP.NET using CSharp

Today I am going to show you how to connect your application with SQL Server 2000 using CSharp and ASP.NET. As we know that CSharp and VB.NET are different from each other in many sense so as there are many other rules to connect your application with database using CSharp. The way we are importing namespace in CSharp is different than VB.NET, in VB.NET we are importing namespace using ‘imports’ keyword but here in CSharp we have to use ‘using’ keyword instead of ‘imports’. VB.NET is not case-sensitive while CSharp is case-sensitive, whenever you are using any class name at that time you have to use the same name as class is defined otherwise you will get error.

Let us see how to connect with database using CSharp. As we know that we have to import required namespace for our application to run. When you are going to connect your application with database you have to import one namespace which is ‘System.Data.SqlClient’. Now view the below mentioned code and try to connect your application with database, I have also provided line by line explanation of each code which will help you in case of any problem.



//always writes your code in try and catch block
//Connection string to connect with database
SqlConnection SQLConn = new SqlConnection("Data Source=IP Address of server;Network Library=DBMSSOCN;Initial Catalog=DatabaseName;User ID=Username of Database;Password=Password of Database;");

//Open connection with database
string query;

// your code comes here
query = "select * from table name”
SqlCommand com = new SqlCommand(query, SQLConn);
SqlDataReader reader = com.ExecuteReader();
reader = com.ExecuteReader();

//Your logic comes here below line will execute as many time as there
//are record available in database

// it is compulsory to close connection after opening it.

//All try block must have one catch block.
catch (Exception ex)

Using above given code you can connect with database and you can retrieve records from your database. I hope that above given code will help you when you want connection with your database.

(Posted By Aden)

ASP. Net Hosting