Your code doesn't make sense. There are a few try-catch block in your code which are unnecessary and you don't have to manually close and dispose the connection. Just use the
Using statement to automatically closes and disposes object that eat resources such as
SqlConnection
and
SqlCommand
. If you are trying to create a method that executes a query command then you can simply do something like this:
private static void ExecuteCommand(string sqlString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
using(SqlCommand command = new SqlCommand(sqlString, connection))
{
command.Connection.Open();
command.ExecuteNonQuery();
}
}
}
You can just then simply call the ExecuteCommand method by passing your sql statement and connectionstring:
ExecuteCommand("YourSqlStatement","YourConnectionString");
Of course, you can still refactor the code to call your
ConnectionString
internally so you don't have to pass the connection string value everytime you call the
ExcuteCommand
method.