Binu,
You have a variety of problems in your code. First, you should not embed your connection string in code - you should pull it from a Config file so that you can change it when you deploy. Second, don't log in to your database with the sa account!! Just don't do it - trust me on this one.
Third, I'd strongly recommend that you use an IDisposable interface and a Using block to ensure that your connection is always closed. As it is, you are depending on the consuming code to call closeConnection.
Try this sample code:
public class MyConnClass : IDisposable
{
public static string ConnectionString { get; set; }
protected SqlConnection conn;
public MyConnClass()
{
conn = new SqlConnection(ConnectionString);
conn.Open();
}
public void Dispose()
{
conn.Close();
}
}
In your initialization code (e.g. Global.asax.cs in a Web app) set the static connection string as follows:
MyConnClass.ConnectionString = ConnectionString;
In your consuming classes you'll use something like:
using (MyConnClass myConn = new MyConnClass())
{
// Database code
}
Update: The other thing I would suggest that you consider is to modify the above code so that it forms the basis for a Data Access Layer (DAL) and not just the Connection. That is, place a SQL command object in there as well and create code to simplify your overall data access strategy. That is, just putting the Connection in a separate class is a bit useless because, as Joel points out, SqlConnection objects are themselves Disposable. The advantage of a full blown DAL is that it can radically simplify your data access. For example, my DAL let's me write things like:
using (MyQueryClass myQuery = new MyQueryClass())
{
myQuery.Command("Update...").ParamVal("@P1", 1).ParamVal("@P2", 2).Execute();
return myQuery.Command("Select ...").ParamVal("@Param", SomeVal).ReturnList<SomeType>();
}
You won't end up with the class that I did but hopefully you can see a few things: the connection string is never an issue in my code (it is encapsulated), I can run multiple commands without all the set up and tear down usually required, and the overall syntax is more fluent.