using (SqlConnection sqlCon = SqlServerBeans.My_con)
{
SqlCommand command = new SqlCommand();
command.Connection = sqlCon;
//sqlCon.Open();
SqlTransaction trans = sqlCon.BeginTransaction();
try
{
foreach (readText.sysChecklist sc in rptd_alst)
{//
count++;
#region SQL字符串 insSql
StringBuilder sb = new StringBuilder("insert into tb1 values( '");
sb.Append("'same string')");//
#endregion
string insSql = sb.ToString();
Console.WriteLine(count + " _$_ " + insSql);
command.CommandText = insSql;
//cm.CommandTimeout = 20;
command.Transaction = trans;
command.ExecuteNonQuery();
}//foreach end
trans.Commit();
//将这张表,表头成功状态
string uptSql = "update [tbHead] set [RptStatus] ='OK' where [ImpID] = " + strImpId;
beans.getsqlcom(uptSql);
MessageBox.Show("导入成功!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
MessageBox.Show("导入不成功", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning );
// Attempt to roll back the transaction.
try
{
trans.Rollback();
}
catch (Exception ex2)
{
// This catch block will handle any errors that may have occurred
// on the server that would cause the rollback to fail, such as
// a closed connection.
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
}
}
使用事务的代码
最新推荐文章于 2024-05-11 01:12:48 发布