Ramco Ramco

Ramco Ramco

  • 419
  • 3.4k
  • 527.9k

Connection Open

Apr 9 2024 5:12 AM

Hi

I have below code & i want connection to be opened only once with Try Catch statement. If Category ID already exists it should not be added.

string constr = ConfigurationManager.ConnectionStrings["Cnn"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
    string query = "INSERT INTO Category VALUES (@CategoryId,@CategoryName)";
    using (SqlCommand cmd = new SqlCommand(query))
    {
        cmd.Connection = con;
        cmd.Parameters.AddWithValue("@CategoryId", data.id);
        cmd.Parameters.AddWithValue("@CategoryName", data.snippet.title);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }
}

Thanks


Answers (2)