1.事务的建立
SqlConnection sqlConnection = new SqlConnection();
...初始化连接
// 开启事务
SqlTransaction sqlTransaction = sqlConnection.BeginTransaction();
// 将事务应用于Command
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.Transaction = sqlTransaction;
try
{
// 利用sqlcommand进行数据操作
...
// 成功提交
sqlTransaction.Commit();
}
catch(Exception ex)
{
// 出错回滚
sqlTransaction.Rollback();
}
2.
public void SaveCITToDataBase(string filename)
{
List<List<object>> CitReport = ReaderCIT(filename);
CitReport.RemoveAt(0);
SqlConnection con = new SqlConnection(AppConfiguration.CITConnectionString);
SqlCommand com = new SqlCommand();
com.Connection = con;
con.Open();
SqlTransaction tran = con.BeginTransaction();
com.Transaction = tran;
string sql = string.Empty;
try
{
foreach (List<object> item in CitReport)
{
sql = "insert into citreport values(";
for (int i = 0; i < item.Count; i++)
{
if (i == 0)
{
sql += "'" + Convert.ToString(item[i]) + "'";
}
else
{
sql += "," + "'" + Convert.ToString(item[i]) + "'";
}
}
sql += ",'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "')";
com.CommandText = sql;
com.ExecuteNonQuery();
}
tran.Commit();
com.Dispose();
}
catch (Exception ex)
{
tran.Rollback();
throw ex;
}
finally { con.Close(); tran.Dispose(); con.Dispose(); }
}