.NET 使用事物调用存储过程
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PricipalPractice { public static class SqlHelper { //根据config配置文件中提供程序,获取数据库连接对象 //private static DbConnection GetDataBaseConnection(string databaseName) //{ // ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[databaseName]; // DbProviderFactory factory = DbProviderFactories.GetFactory(settings.ProviderName); // DbConnection conn = factory.CreateConnection(); // conn.ConnectionString = settings.ConnectionString; // return conn; //} //事物的使用,调用存储过程,无返回值 private static void ExecuteTransaction() { string dataBaseName = "databaseName"; using (SqlConnection con = GetDataBaseConnection(dataBaseName)) { con.Open(); using (SqlCommand command = con.CreateCommand()) { SqlTransaction st = con.BeginTransaction(); command.Transaction = st; try { command.CommandText = "storeName"; command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("@param", "value")); command.ExecuteNonQuery(); st.Commit(); } catch (Exception ex) { st.Rollback(); throw new Exception(ex.Message); } } con.Close(); } } private static SqlConnection GetDataBaseConnection(string databaseName) { ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[databaseName]; return new SqlConnection(settings.ConnectionString); } } }