I have a handler class for every table and I am doing all the DB work in functions, like below.
public class MyObjectHandler
{
public bool Insert(MyObject obj)
{
using(SqlConnection conn = new SqlConnection(DbHandler.ConnectionString))
{
SqlCommand comm = new SqlCommand("OBJ_INSERT", conn);
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add(new SqlParameter("@Code", SqlDbType.NVarChar, 50) { Value = obj.Code });
comm.Parameters.Add(new SqlParameter("@Desc", SqlDbType.NVarChar, 150) { Value = obj.Desc });
comm.Parameters.Add(new SqlParameter("@UserId", SqlDbType.Int) { Value = obj.UserCreated.Id });
conn.Open();
int retVal = comm.ExecuteNonQuery();
conn.Close();
if(retVal > 0)
return true;
else
return false;
}
}
public bool Update(MyObject obj)
{
using(SqlConnection conn = new SqlConnection(DbHandler.ConnectionString))
{
SqlCommand comm = new SqlCommand("OBJ_UPDATE", conn);
comm.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = obj.Id });
comm.Parameters.Add(new SqlParameter("@Code", SqlDbType.NVarChar, 50) { Value = obj.Code });
comm.Parameters.Add(new SqlParameter("@Desc", SqlDbType.NVarChar, 150) { Value = obj.Desc });
comm.CommandType = CommandType.StoredProcedure;
conn.Open();
int retVal = comm.ExecuteNonQuery();
conn.Close();
if(retVal > 0)
return true;
else
return false;
}
}
public bool Delete(int Id)
{
using(SqlConnection conn = new SqlConnection(DbHandler.ConnectionString))
{
SqlCommand comm = new SqlCommand("OBJ_DELETE", conn);
comm.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = Id });
comm.CommandType = CommandType.StoredProcedure;
conn.Open();
int retVal = comm.ExecuteNonQuery();
conn.Close();
if(retVal > 0)
return true;
else
return false;
}
}
}
Problem is, as you can see I am using SqlConnection
routine all the time.
I want to create a layer, which is a class that includes all the SQL libraries.
Would you offer me a general solution on this? Even a general idea will be enough on this.
For example, my function for Getting the data is easy:
public static DataTable GetDataTable(string spName)
{
DataTable resultsTable = new DataTable();
using(SqlConnection conn = new SqlConnection(DbHandler.ConnectionString))
{
SqlCommand comm = new SqlCommand(spName, conn);
comm.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter(comm);
adapter.Fill(resultsTable);
conn.Close();
}
return resultsTable;
}
This is good enough, but I need a better solution to send parameters easily and with more flexibility. Seems like the only option is to send parameter name, type and length one by one. Would you recommend a design on this?