Hi,
I am developing an application which will be connected to Access database at the beginning and the plan is to switch to MS SQL or SQL Express in the near future. The datatables structures are same for both types of databases and I am trying to avoid duplicating the code and trying to find the way to minimize the code.
For example I wrote the following function for retrieving data from Access database:
public static DataTable GetActiveCalls()
{
string select = "SELECT call_id, call_time, msisdn, status FROM call WHERE status = 0 OR status = 1 ORDER by call_id ASC";
OleDbCommand cmd = new OleDbCommand(select, conn);
DataTable dt = new DataTable("Active Calls");
OleDbDataAdapter DA = new OleDbDataAdapter(cmd);
try
{
conn.Open();
DA.Fill(dt);
}
catch (Exception ex)
{
string sDummy = ex.ToString();
}
finally
{
conn.Close();
}
return dt;
}
and the following code is for SQL Express database:
public static DataTable GetActiveCalls()
{
string select = "SELECT call_id, call_time, msisdn, status FROM call WHERE status = 0 OR status = 1 ORDER by call_id ASC";
SqlCommand cmd = new SqlCommand(select, conn);
DataTable dt = new DataTable("Active Calls");
SqlDataAdapter DA = new SqlDataAdapter(cmd);
try
{
conn.Open();
DA.Fill(dt);
}
catch (Exception ex)
{
string sDummy = ex.ToString();
}
finally
{
conn.Close();
}
return dt;
}
These two methods are almost the same. The only differences are SqlCommand/OleDbCommand and SqlDataAdapter/OleDbDataAdapter. There are also some methods which take arguments for example:
public static void AddMessage(string callID, string content)
{
string select =
"INSERT INTO message(key, direction, content, read, write_time) VALUES (@callId, 0, @content, 0, @insertTime)";
OleDbCommand cmd = new OleDbCommand(select, conn);
cmd.Parameters.AddWithValue("callId", callID.ToString());
cmd.Parameters.AddWithValue("content", content);
cmd.Parameters.AddWithValue("insertTime", DateTime.Now.ToString());
try
{
conn.Open();
cmd.ExecuteScalar();
}
catch (Exception ex)
{
string sDummy = ex.ToString();
}
finally
{
conn.Close();
}
}
In this case SQL query string is also the same for both databases but there is the difference between the type of cmd (SqlCommand/OleDbCommand).
I would really appreciate if anyone could give any suggestion about how to avoid duplicating the code and optimize the given problem.