I\'m having an issue at the moment which I am trying to fix. I just tried to access a database and insert some values with the help of C#
The things I tried (worked)
I have just wrote a reusable method for that, there is no answer here with reusable method so why not to share...
here is the code from my current project:
public static int ParametersCommand(string query,List parameters)
{
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{ // for cases where no parameters needed
if (parameters != null)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
connection.Open();
int result = cmd.ExecuteNonQuery();
return result;
}
}
catch (Exception ex)
{
AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
return 0;
throw;
}
finally
{
CloseConnection(ref connection);
}
}
private static void CloseConnection(ref SqlConnection conn)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}