I have a static class in my code that has two methods that store different data in a SQL database when they are called. In each of the methods I open a connection to the database. Is this the proper way to do it or is there a better way to do it?
My Code
using System.Data.SqlClient;
namespace Asm
{
internal static class StoreCheckBoxResult
{
internal static void StoreCheckBoxInDB(int lineNumber, bool result, string imagePath)
{
string connectionString = Environment.GetEnvironmentVariable("DB_CONNECTION"); ;
SqlConnection Connection = new SqlConnection(connectionString);
SqlCommand Command = Connection.CreateCommand();
Command.CommandText = string.Format("UPDATE [dbo].[ASM_JSON] SET CheckBox{0} = '{1}' WHERE ImagePath = '{2}'", lineNumber, result, imagePath);
try
{
Connection.Open();
Command.ExecuteNonQuery();
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
Connection.Close();
}
internal static void StoreCheckBoxCoords(int lineNumber, int[] coords, string imagePath)
{
string connectionString = Environment.GetEnvironmentVariable("DB_CONNECTION"); ;
SqlConnection Connection = new SqlConnection(connectionString);
SqlCommand Command = Connection.CreateCommand();
string coordString = string.Format("{0},{1} | {2}, {3} | {4}, {5} | {6}, {7}", coords[0], coords[1], coords[2], coords[3], coords[4], coords[5], coords[6], coords[7]);
Command.CommandText = string.Format("UPDATE [dbo].[ASM_JSON] SET CheckBoxCoords{0} = '{1}' WHERE ImagePath = '{2}'", lineNumber, coordString, imagePath);
try
{
Connection.Open();
Command.ExecuteNonQuery();
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
Connection.Close();
}
}
}