View Code
public void ExecuteSqlTran(List<String> ListNews, List<String> ListNews1)
{
string connectionString = ConfigurationManager.ConnectionStrings["News"].ToString();
string connectionString1 = ConfigurationManager.ConnectionStrings["News1"].ToString();
SqlConnection sqlcon = new SqlConnection(connectionString);
SqlConnection sqlcon1 = new SqlConnection(connectionString1);
sqlcon.Open();
SqlCommand sqlcmd = new SqlCommand();
sqlcmd.Connection = sqlcon;
SqlTransaction sqltr = sqlcon.BeginTransaction();
sqlcmd.Transaction = sqltr;
sqlcon1.Open();
SqlCommand sqlcmd1 = new SqlCommand();
sqlcmd1.Connection = sqlcon1;
SqlTransaction sqltr1 = sqlcon1.BeginTransaction();
sqlcmd1.Transaction = sqltr1;
try
{
foreach (String str in ListNews)
{
if (str.Trim().Length > 0)
sqlcmd.CommandText = str;
sqlcmd.ExecuteNonQuery();
}
foreach (String str1 in ListNews1)
{
if (str1.Trim().Length > 0)
sqlcmd1.CommandText = str1;
sqlcmd1.ExecuteNonQuery();
}
sqltr1.Commit();
sqltr.Commit();
}
catch (Exception)
{
sqltr1.Rollback();
sqltr.Rollback();
}
sqlcon.Close();
sqlcon1.Close();
}
View Code
public void ExecuteSqlTran(List<String> ListNews)
{
string connectionString = ConfigurationManager.ConnectionStrings["News"].ToString();
using (SqlConnection sqlcon = new SqlConnection(connectionString))
{
sqlcon.Open();
using (SqlCommand sqlcmd = new SqlCommand())
{
sqlcmd.Connection = sqlcon;
SqlTransaction sqltr = sqlcon.BeginTransaction();
sqlcmd.Transaction = sqltr;
try
{
foreach (String str in ListNews)
{
if (str.Trim().Length > 0)
sqlcmd.CommandText = str;
sqlcmd.ExecuteNonQuery();
}
sqltr.Commit();
}
catch (Exception)
{
sqltr.Rollback();
sqlcon.Close();
}
}
}
}
第一个是创建二个数据库连接分别操作事务
第二个是创建一个连接事务
第一种方式测试
View Code
List<String> NewsList = new List<string>();
NewsList.Add("INSERT INTO [News] ([Title]) VALUES('这是测试')");
NewsList.Add("INSERT INTO [News] ([Title]) VALUES('这是测试1')");
NewsList.Add("INSERT INTO [News] ([Title]) VALUES('这是测试2')");
NewsList.Add("INSERT INTO [News] ([Title]) VALUES('这是测试3')");
List<String> NewsList1 = new List<string>();
NewsList1.Add("INSERT INTO [News1] ([Title]) VALUES('这是测试')");
NewsList1.Add("INSERT INTO [News1] ([Title]) VALUES(这是测试1')");
NewsList1.Add("INSERT INTO [News1] ([Title]) VALUES(这是测试2')");
NewsList1.Add("INSERT INTO [News1] ([Title]) VALUES('这是测试3')");
new DB().ExecuteSqlTran(NewsList, NewsList1);
第二种试测试
View Code
List<String> NewsList = new List<string>();
NewsList.Add("INSERT INTO [News] ([Title]) VALUES('这是测试')");
NewsList.Add("INSERT INTO [News1]..[News1] ([Title]) VALUES('这是测试1')");
new DB().ExecuteSqlTran(NewsList);
第二种方式注意上面的插入时候的数据库和表 方法是 数据库..表名
如果SQL执行失败事务回滚 其实就相当于在数据库中执行了插入删除操作