作者:卞功鑫 ,轉載請保留http://www.cnblogs.com/BinBinGo/p/6399847.html
//1 連接字符串 string connectionString = "server=127.0.0.1;integrated security=true;database=MSPetShop4"; // = "server=.;uid=sa;pwd=SQL@5;database=AdventureWorks2012"; // = "server=.;user id=sa;password=SQL@5;database=AdventureWorks2012"; //2 實例化數據庫連接 System.Data.SqlClient.SqlConnection connection = new SqlConnection(connectionString); //也可以先實例化 //System.Data.SqlClient.SqlConnection connection = new SqlConnection(); //然后再設置ConnectionString 屬性. //connection.ConnectionString = connectionString; try { //3 打開連接 connection.Open(); Console.WriteLine("成功連接數據計庫MSPetShop4"); //4 數據訪問對象 //sql字符串存儲過程 string sql = "p_proc_name"; /* create proc p_proc_name (@pin INT ,@pout INT OUTPUT) AS delete FROM dbo.A WHERE 客戶='biangongxin' SET @pout = @pin*100; */ //SqlCommand 表示數據庫要執行的sql命令 System.Data.SqlClient.SqlCommand command = new SqlCommand(sql, connection); //告知數據庫現在要執行的是存儲過程 //默認為標准SQL語句,可以不用設置. command.CommandType = CommandType.StoredProcedure; //提供存儲過程參數(傳入參數) 這里的名稱@pin和存儲過程中的保持一致 System.Data.SqlClient.SqlParameter pin = new SqlParameter("@pin", System.Data.SqlDbType.Int); //參數賦值 pin.Value = 10; //將上面的參數加入command中 command.Parameters.Add(pin); //提供存儲過程參數(傳出參數)這里的名稱@pout和存儲過程中的保持一致 System.Data.SqlClient.SqlParameter pout = new SqlParameter("@pout", System.Data.SqlDbType.Int); //聲明為傳出參數 Direction 參數方向 ,默認為傳入參數 ParameterDirection.Input pout.Direction = ParameterDirection.Output; //將上面的參數加入command中 command.Parameters.Add(pout); //ExecuteNonQuery 非查詢語句 //默認工作在自動事務之下,直接提交 //執行sql DML 之前,手動開啟 System.Data.SqlClient.SqlTransaction trans = connection.BeginTransaction(); //設置命令所屬的事務管理 command.Transaction = trans; int result = command.ExecuteNonQuery(); Console.WriteLine(result); //存儲過程執行過之后,可以得到傳出的參數(存儲過程執行的時候,會把sql中的 output的這個參數的值賦值給C#中的 pout) object obj = pout.Value; int p_result = Convert.ToInt32(obj); Console.Write("SQL命令已經提交,但是事務還未提交,是否繼續執行(Y/N)"); string ans = Console.ReadLine(); //提交與否@pout值的返回值始終為1000,影響的只是 SQL的 DML操作 if (ans.Substring(0, 1).ToUpper() == "Y") { //提交事務 trans.Commit(); } else { //回滾事務; trans.Rollback(); } Console.WriteLine("存儲過程p_proc_name,執行的結果為:{0}",p_result); } catch(System.Data.SqlClient.SqlException exception) { Console.WriteLine(exception.Message); } finally { //4 注銷連接 connection.Dispose(); Console.WriteLine("成功斷開數據計庫MSPetShop4"); } Console.ReadLine();
