I am new to ADO, so I want to ask if I did right using transaction. Here the code snippet
string SQL1 = "INSERT INTO tbl_cust(cust_id,cust_name) values ('000001','YoungMcD') ";
string SQL2 = "UPDATE tbl_cust SET custname='OldMcDonald' WHERE cust_id='000001'";
string SQL3 = "SELECT * FROM tbl_supplier WHERE supplier_code ='000001'";
// write connstring
string conn = System.Configuration.ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
// end of connection string
// setting connection
SqlConnection db = new SqlConnection(conn);
SqlTransaction transaction1;
db.Open();
transaction1 = db.BeginTransaction();
try
{
// insert to table
SqlCommand Com1 = new SqlCommand(SQL1, db, transaction1);
Com1.ExecuteNonQuery();
SqlCommand Com2 = new SqlCommand(SQL2, db, transaction1);
Com2.ExecuteNonQuery();
SqlCommand Com3 = new SqlCommand(SQL3, db, transaction1);
Com3.ExecuteNonQuery();
transaction1.Commit();
db.Close();
}
catch
{
transaction1.Rollback();
db.Close();
msg = "error";
goto endret;
}
For transaction, should I use
SqlCommand Com1 = new SqlCommand(SQL1, db, transaction1);
instead of
SqlCommand Com1 = new SqlCommand(SQL1, db);
because I already state begin transaction before try{} statement
EDIT:
I get it, First syntax is applicable, but how to use ADO effectively?. I find that this way is too straightforward.
I found myself keep doing this for inserting parameter, ex:
string SQL1 = "INSERT INTO tbl_cust(cust_id,cust_name) values ('" + param1 +"','"+ param2 +"') ";
db.Close()will cause the code to try to rollback a transaction? This is clearly wrong. Movedb.Close()outside thetry..catchblock.