I'm writing a C# program with SQL Server and SQL Server CE. How can I avoid writing same code like below, variable databasestate is used to see if program should use SQL Server or SQL Server CE.
public static void Delete()
{
SqlCeCommand commce = new SqlCeCommand("Delete From Projekat WHERE IDProjekat = @ConID", conce);
SqlCommand comm = new SqlCommand("Delete From Projekat WHERE IDProjekat = @ConID", con);
if (CrossFormData.databasestate == false)
{
commce.Parameters.AddWithValue("@ConID", CrossFormData.ProjectID);
try
{
conce.Open();
commce.ExecuteNonQuery();
conce.Close();
MessageBox.Show("Deleted!");
}
catch (Exception)
{
MessageBox.Show("Something went wrong");
conce.Close();
}
}
else
{
comm.Parameters.AddWithValue("@ConID", CrossFormData.ProjectID);
try
{
con.Open();
comm.ExecuteNonQuery();
con.Close();
MessageBox.Show("Deleted!");
}
catch (Exception)
{
MessageBox.Show("Something went wrong");
con.Close();
}
}
}
If using SQL Server CE is making you angry, I'm sorry next time I will use SQLite.
If I don't find a way I will separate them in two different classes so it's more organized.
con.Close();should be in afinallyblock if you are not using ausing.