Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone
 

Registered : 109,027

HOME > บทความจากสมาชิก > Query ข้อมูลจาก SQL Server เป็น JSON และการ Deserialize (Decode) ข้อมูล (VB.Net,C#)



 
Clound SSD Virtual Server

Query ข้อมูลจาก SQL Server เป็น JSON และการ Deserialize (Decode) ข้อมูล (VB.Net,C#)

Query ข้อมูลจาก SQL Server เป็น Json และการ Deserialize (Decode) ข้อมูล (VB.Net,C#) ปัจจุบันการใช้ Json ได้รับความนิยมอย่างมาก และประยุกต์ใช้กับการเขียนโปรแกรมได้มากมาย ไม่จำเป็นว่าจะต้องใช้สำหรับการส่งค่าระหว่าง Application แต่สามารถนำมาใช้สำหรับการรับส่งค่าระหว่าง Database กับ Application โดยตรง ซึ่งจะสะดวกในกรณีที่ต้องการส่ง Result มาในรูปแบบของข้อความชุด และด้วยเหตุนี้เองใน SQL Server 2016 มีการเพิ่มฟีเจอร์ของการแปลงข้อมูลจาก Query เป็น Json ได้ทันที แต่ถ้าในเวอร์ชั่นที่ตำกว่า 2016 อาจจะต้องใช้การ SELECT แล้วนำมา STUFF ให้อยู่ในรูปแบบของข้อความ Json ก่อนที่จะนำไปใช้ โดยอาจจะเขียน Query จาก Stored Procedure ซึ่งมันจะสามารถ Return OUTPUT ออกมาในรูปแบบของ String ทั่ว ๆ ไป แล้วค่อยนำค่าที่ได้ไปใช้งานกับ Application อื่น ๆ หรือจะใช้การ Deserialize ก็สามารถทำได้ง่าย ๆ เช่นเดียวกัน



SQL Server and JSON Deserialize (Decode)


บทความนี้จะยกตัวอย่างการเขียน Stored Procedure เพื่อ Query ข้อมูลจาก Table ให้อยู่ในรูปแบบของ Json จากนั้นใช้ VB.Net และ C# ทำการ Execute ตัว Stored Procedure ซึ่งจะได้ OUTPUT ข้อความ Json กลับมา

Table : Employee
CREATE TABLE [dbo].[Employee2](
	[EmpID] [varchar](10) NOT NULL,
	[Name] [varchar](250) NULL,
	[Email] [varchar](250) NULL,
 CONSTRAINT [PK_Employee2] PRIMARY KEY CLUSTERED 
(
	[EmpID] ASC
))

01

โครงสร้างของ Table : Employee








การ Select ให้อยู่ในรูปแบบของ Json
	SELECT @sJson = '[' + STUFF((
			SELECT 
				',{"EmpID":"' + CAST(EmpID AS VARCHAR(4)) + '"'
				+ ',"Name":"' + CAST(Name AS VARCHAR(250)) + '"'
				+ ',"Email":"' + CAST(Email AS VARCHAR(250)) + '"'
				+'}'
			FROM Employee ORDER BY EmpID ASC
			FOR XML PATH(''), TYPE
		).value('.', 'VARCHAR(MAX)'), 1, 1, '') + ']'


02

เนื่องจากบทความนี้จะมีการใช้งาน Deserialize Json ด้วย ฉะนั้นให้ Add Reference ตัว Newtonsoft.Json มาใช้งาน

03

ติดตั้ง Newtonsoft.Json

04

Newtonsoft.Json

Stored Procedure : getEmployee
CREATE PROCEDURE [dbo].[getEmployee]
	@sJson	VARCHAR(MAX) OUT
AS
BEGIN
	

	SELECT @sJson = '[' + STUFF((
			SELECT 
				',{"EmpID":"' + CAST(EmpID AS VARCHAR(4)) + '"'
				+ ',"Name":"' + CAST(Name AS VARCHAR(250)) + '"'
				+ ',"Email":"' + CAST(Email AS VARCHAR(250)) + '"'
				+'}'
			FROM Employee ORDER BY EmpID ASC
			FOR XML PATH(''), TYPE
		).value('.', 'VARCHAR(MAX)'), 1, 1, '') + ']'

END
GO
สร้าง Stored Procedure ชื่อว่า getEmployee

Ex 1 : การเรียกใช้งาน Stored Procedure เพื่อดึงค่า Json มาใช้งาน

C#
        protected void Page_Load(object sender, EventArgs e)
        {

            SqlConnection objConn = new SqlConnection();
            SqlCommand objCmd = new SqlCommand();

            String strConnString, strStored;
            string strJson = string.Empty;

            strConnString = "Server=localhost;UID=sa;PASSWORD=mypassword;database=mydatabase; " +
            " Max Pool Size=400;Connect Timeout=600;";
            objConn.ConnectionString = strConnString;
            objConn.Open();


            strStored = "getEmployee";
            objCmd.Parameters.Add(new SqlParameter("sJson", SqlDbType.VarChar, 8000)).Direction = ParameterDirection.Output; // OUT

            objCmd.Connection = objConn;
            objCmd.CommandText = strStored;
            objCmd.CommandType = CommandType.StoredProcedure;

            objCmd.ExecuteNonQuery();

            // Get json result 
            strJson = objCmd.Parameters["sJson"].Value.ToString();
            ltJson.Text = strJson;

            objConn.Close();
            objConn = null;

        }

VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim objConn As New SqlConnection()
        Dim objCmd As New SqlCommand()

        Dim strConnString As [String], strStored As [String]
        Dim strJson As String = String.Empty

        strConnString = "Server=localhost;UID=sa;PASSWORD=mypassword;database=mydatabase; " + " Max Pool Size=400;Connect Timeout=600;"
        objConn.ConnectionString = strConnString
        objConn.Open()


        strStored = "getEmployee"
        objCmd.Parameters.Add(New SqlParameter("sJson", SqlDbType.VarChar, 8000)).Direction = ParameterDirection.Output
        ' OUT
        objCmd.Connection = objConn
        objCmd.CommandText = strStored
        objCmd.CommandType = CommandType.StoredProcedure

        objCmd.ExecuteNonQuery()

        ' Get json result 
        strJson = objCmd.Parameters("sJson").Value.ToString()
        ltJson.Text = strJson

        objConn.Close()
        objConn = Nothing

End Sub

Result

05

ตัวอย่างข้อความ Json ที่ได้จาก SQL Server








Ex 2 : การเรียกใช้งาน Deserialize (Decode) ให้อยู่ในรูปแบบของ List(T) เพื่อนำไปใช้กับ Datasource

            var lsEmployee = JsonConvert.DeserializeObject<List<Employee>>(strJson);
            this.myGridView.DataSource = lsEmployee;
            this.myGridView.DataBind();


C#
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using Newtonsoft.Json;

namespace SQLServerJSON
{
    public partial class myWebForm : System.Web.UI.Page
    {

        public class Employee
        {
            public string EmpID { get; set; }
            public string Name { get; set; }
            public string Email { get; set; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            SqlConnection objConn = new SqlConnection();
            SqlCommand objCmd = new SqlCommand();

            String strConnString, strStored;
            string strJson = string.Empty;

            strConnString = "Server=localhost;UID=sa;PASSWORD=mypassword;database=mydatabase; " +
            " Max Pool Size=400;Connect Timeout=600;";
            objConn.ConnectionString = strConnString;
            objConn.Open();


            strStored = "getEmployee";
            objCmd.Parameters.Add(new SqlParameter("sJson", SqlDbType.VarChar, 8000)).Direction = ParameterDirection.Output; // OUT

            objCmd.Connection = objConn;
            objCmd.CommandText = strStored;
            objCmd.CommandType = CommandType.StoredProcedure;

            objCmd.ExecuteNonQuery();

            // Get json result 
            strJson = objCmd.Parameters["sJson"].Value.ToString();
            //ltJson.Text = strJson;

            objConn.Close();
            objConn = null;

            var lsEmployee = JsonConvert.DeserializeObject<List<Employee>>(strJson);
            this.myGridView.DataSource = lsEmployee;
            this.myGridView.DataBind();

        }
    }
}

VB.Net
Imports System.Data.SqlClient
Imports System.Data
Imports Newtonsoft.Json

Public Class myWebForm
    Inherits System.Web.UI.Page

    Public Class Employee
        Public Property EmpID() As String
            Get
                Return m_EmpID
            End Get
            Set
                m_EmpID = Value
            End Set
        End Property
        Private m_EmpID As String
        Public Property Name() As String
            Get
                Return m_Name
            End Get
            Set
                m_Name = Value
            End Set
        End Property
        Private m_Name As String
        Public Property Email() As String
            Get
                Return m_Email
            End Get
            Set
                m_Email = Value
            End Set
        End Property
        Private m_Email As String
    End Class

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim objConn As New SqlConnection()
        Dim objCmd As New SqlCommand()

        Dim strConnString As [String], strStored As [String]
        Dim strJson As String = String.Empty

        strConnString = "Server=localhost;UID=sa;PASSWORD=mypassword;database=mydatabase; " + " Max Pool Size=400;Connect Timeout=600;"
        objConn.ConnectionString = strConnString
        objConn.Open()


        strStored = "getEmployee"
        objCmd.Parameters.Add(New SqlParameter("sJson", SqlDbType.VarChar, 8000)).Direction = ParameterDirection.Output
        ' OUT
        objCmd.Connection = objConn
        objCmd.CommandText = strStored
        objCmd.CommandType = CommandType.StoredProcedure

        objCmd.ExecuteNonQuery()

        ' Get json result 
        strJson = objCmd.Parameters("sJson").Value.ToString()
        'ltJson.Text = strJson

        objConn.Close()
        objConn = Nothing

        Dim lsEmployee = JsonConvert.DeserializeObject(Of List(Of Employee))(strJson)
        Me.myGridView.DataSource = lsEmployee
        Me.myGridView.DataBind()

    End Sub

End Class

Result

06


.


   
Share
Bookmark.   

  By : TC Admin
  Article : บทความเป็นการเขียนโดยสมาชิก หากมีปัญหาเรื่องลิขสิทธิ์ กรุณาแจ้งให้ทาง webmaster ทราบด้วยครับ
  Score Rating :
  Create Date : 2016-12-21
  Download : No files
Sponsored Links
ThaiCreate.Com Forum


Comunity Forum Free Web Script
Jobs Freelance Free Uploads
Free Web Hosting Free Tools

สอน PHP ผ่าน Youtube ฟรี
สอน Android การเขียนโปรแกรม Android
สอน Windows Phone การเขียนโปรแกรม Windows Phone 7 และ 8
สอน iOS การเขียนโปรแกรม iPhone, iPad
สอน Java การเขียนโปรแกรม ภาษา Java
สอน Java GUI การเขียนโปรแกรม ภาษา Java GUI
สอน JSP การเขียนโปรแกรม ภาษา Java
สอน jQuery การเขียนโปรแกรม ภาษา jQuery
สอน .Net การเขียนโปรแกรม ภาษา .Net
Free Tutorial
สอน Google Maps Api
สอน Windows Service
สอน Entity Framework
สอน Android
สอน Java เขียน Java
Java GUI Swing
สอน JSP (Web App)
iOS (iPhone,iPad)
Windows Phone
Windows Azure
Windows Store
Laravel Framework
Yii PHP Framework
สอน jQuery
สอน jQuery กับ Ajax
สอน PHP OOP (Vdo)
Ajax Tutorials
SQL Tutorials
สอน SQL (Part 2)
JavaScript Tutorial
Javascript Tips
VBScript Tutorial
VBScript Validation
Microsoft Access
MySQL Tutorials
-- Stored Procedure
MariaDB Database
SQL Server Tutorial
SQL Server 2005
SQL Server 2008
SQL Server 2012
-- Stored Procedure
Oracle Database
-- Stored Procedure
SVN (Subversion)
แนวทางการทำ SEO
ปรับแต่งเว็บให้โหลดเร็ว


Hit Link
   







Load balance : Server 01
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่