C#中经常需要写Sql 的事务,基于MSSql,Function:
using System.Data.SqlClient;
private void test()
{
List<string> sqllist = new List<string>();
StringBuilder strSql = new StringBuilder();
sqllist.Add(string.Format(@”INSERT INTO [dbo]. [Table_a]([name],[num])VALUES(‘cpp3’,21);”));
sqllist.Add(string.Format(@”INSERT INTO [dbo].[Table_a]([name],[num])VALUES(‘cpp2’,22);”));
foreach (string i in sqllist)
{
strSql.Append(i);
}
SqlConnection conn = new SqlConnection(sql_helper.ConString);
conn.Open();
SqlTransaction tran = conn.BeginTransaction();
try
{
sql_helper.ExecuteNonQuery(tran, CommandType.Text, strSql.ToString(), null);
tran.Commit();
Console.WriteLine(“OK”);
}
catch (Exception ex)
{
tran.Rollback();
Console.WriteLine(“Error”);
Console.Beep();
}
finally
{
conn.Close();
}
}