.net sql->cmd->apt->json

  • 113
  • 0

SQL ->  SqlCommand ->  SqlDataAdapter ->  DataTable -> JSON

 

namespace Pratice_Extjs
{
    public partial class WebForm8 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string sql = "";
            string outJSONString = "";
            SqlDataAdapter apt;
            DataTable dt;
            string con_str = ConfigurationManager.ConnectionStrings["MyconStr"].ConnectionString;
            SqlConnection con = new SqlConnection(con_str);
            SqlCommand cmd = new SqlCommand("", con);
            SqlTransaction sqltran;
            con.Open();

            #region
            sql = @"
            SELECT 
                *
                ,CONVERT(varchar(10),upd_dt,120)  AS 'x_upd_dt'
            FROM 
                MyTable
            WHERE
                year = @year
            ";
            cmd.CommandText = sql;
            SetCommandParam("@year", "107", cmd);
            apt = new SqlDataAdapter(sql, con);
            apt.SelectCommand = cmd;
            dt = new DataTable();
            apt.Fill(dt);

            // 將 DataTable 轉 Json 字串
            outJSONString = JsonConvert.SerializeObject(dt, Newtonsoft.Json.Formatting.Indented);
            // 回傳至前端
            Response.Write(outJSONString);
            #endregion

        }

        public void SetCommandParam(string ParamName, object ParamValue,SqlCommand cmd)
        {
            if (cmd.Parameters.IndexOf(ParamName) == -1)
            {
                cmd.Parameters.AddWithValue(ParamName, ParamValue);
            }
            else
            {
                cmd.Parameters[ParamName].Value = ParamValue;
            }
        }
    }
}