Im a beginner to .net and for my final year project im developing a payroll system. Now I have some issues regarding ado.net sql connection object.
To keep the connection string centrally I have used a separate class call 'db'. Taking another step to this centralization thinking, Ive initialized the connection object also centrally in this 'db' class as follows.
class db
{
string connectionString = ("server=CHATHURANGA-PC\\SQLEXPRESS;" +
"Trusted_Connection=yes;" +
"database=Payroll; " +
"connection timeout=30");
public SqlConnection GetConn()
{
SqlConnection NewConn = new SqlConnection(connectionString);
return NewConn;
}
}
Now Im using this connection object as follows in my application...
I just want to know whether I would face issues in future because of this practice and also appreciate if one of experts could explain me what is the best practice in this regard.
class client
{
db NewDB = new db();
SqlConnection newCon;
public void addNewClient(DateTime entDate, client NewClient)
{
try
{
newCon = NewDB.GetConn();
string CommandString = "INSERT INTO client(Client_Name, C_Add, Contact_Person, C_Mob_No, C_Tel_No, Remarks, Ent_Date)" +
" VALUES (@CName, @CAdd, @CPerson, @CMob, @CTel, @Remarks, @entDate)";
SqlCommand SqlCom = new SqlCommand();
SqlCom.CommandText = CommandString;
SqlCom.Parameters.Add("@CName", SqlDbType.VarChar).Value = NewClient.CName;
SqlCom.Parameters.Add("@CAdd", SqlDbType.VarChar).Value = NewClient.CAdd;
SqlCom.Parameters.Add("@CPerson", SqlDbType.VarChar).Value = NewClient.CPerson;
SqlCom.Parameters.Add("@CMob", SqlDbType.Char).Value = NewClient.CMob;
SqlCom.Parameters.Add("@CTel", SqlDbType.Char).Value = NewClient.CTel;
SqlCom.Parameters.Add("@Remarks", SqlDbType.VarChar).Value = NewClient.Remarks;
SqlCom.Parameters.Add("@entDate", SqlDbType.Date).Value = entDate;
SqlCom.Connection = newCon;
newCon.Open();
SqlCom.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
newCon.Close();
}
}
}