1. 程式人生 > >應用於Web Service呼叫儲存過程

應用於Web Service呼叫儲存過程

using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient;

namespace DAL { public class DBHelper { private readonly static string connection =”Data Source=.;Initial Catalog=Test;User ID=sa;pwd=123321”;

}
 /// <summary>
    /// 儲存過程增刪改
    /// </summary>
    /// <param name="type"></param>
    /// <param name="procSql"></param>
    /// <param name="par"></param>
    /// <returns></returns>
    public int SqlExec(CommandType type,string proSql,SqlParameter[] par)
    {
//異常處理機制
try
{
    using(Sqlconnection conn = new SqlConnection(connection))
    {
        conn.Open();
        Sqlcommand cmd = new SqlCommand(proSql,conn);
        cmd.CommandType = Type;
        if(par!=null){
            cmd.Parameters.AddRange(par);
        }
        return cmd.ExecuteNonQuery();
    }
}
catch
{
       return -1;
}
    }
    /// <summary>
    /// 儲存過程呼叫
    /// </summary>
    /// <param name="procName"></param>
    /// <param name="par"></param>
    /// <returns></returns>
public DataTable GetProDataTable(CommandType Type,string proName,SqlParameter[] par)
{
    try
    {
        using(SqlConnction conn = new SqlConnection(connection))
        {
             SqlCommand command = new SqlCommand(procName, conn);  //執行SQL語句
                            command.CommandType = type;
                        if (par != null)
                        {
                                command.Parameters.AddRange(par);
                         }
                            SqlDataAdapter sda = new SqlDataAdapter(command);  //介面卡
                         DataTable dt = new DataTable();               //NEW DataTable
                        dt.TableName = "dt";
                            sda.Fill(dt);  //填充資料
                         return dt;
        }
    }
    catch(Exception){return null;}
}

}