private void button2_Click(object sender, EventArgs e)
{
if (OrderIdTb.Text == "" || CustId.Text == "" || CustName.Text == "" || TotAmount.Text == "")
{
MessageBox.Show("Fill The data Correctly");
}
else
{
Con.Open();
SqlCommand cmd = new SqlCommand("Insert into ProductTbl Values(" OrderIdTb.Text "," CustId.Text "," CustName.Text "," orderdate.Text "," TotAmount.Text ")", Con) ;
cmd.ExecuteNonQuery();
MessageBox.Show("Order Added Successfully ");
populate();
Con.Close();
try
{
}
catch
{
}
}
}
CodePudding user response:
it's good habit to write finally block and within that you have close all opened sql connections and try to use Using loop to run the query.
Eg:
SqlConnection sqlconn= null;
SqlCommand sqlcmd= null;
SqlTransaction sqlTrans= null;
SqlDataReader sqlReader= null;
try
{
sqlconn = new SqlConnection("conn string");
sqlconn.Open();
---- Query ---
---- Query ---
---- Query ---
sqlconn.Close()
}
catch(exception ex)
{
}
finally
{
if(sqlReader !=null)
{
sqlReader.close();
sqlReader = null;
}
if(sqlTrans != null)
{
sqlTrans.Dispose();
sqlTrans = null;
}
if(sqlcmd != null)
{
sqlcmd.Dispose();
sqlcmd = null;
}
if( sqlconn != null)
{
sqlconn.Close();
sqlconn = null;
}
}
CodePudding user response:
Create a new connection for each function. Don't try to reuse a database connection, it always ends badly.
using (var con = new SqlConnection(....)){
con.Open();
SqlCommand cmd = new SqlCommand("Insert into ProductTbl Values(" OrderIdTb.Text "," CustId.Text "," CustName.Text "," orderdate.Text "," TotAmount.Text ")", Con) ;
cmd.ExecuteNonQuery();
MessageBox.Show("Order Added Successfully ");
populate();
} //Then end of the using block closes the connection safely, even if there is an error.