簡體   English   中英

通過VB.NET和JSON進行SQL查詢

[英]SQL queries through VB.NET and JSON

我對VB.NET和JSON都是全新的,我正在試圖弄清楚如何對SQL 2005 Express服務器進行SQL查詢並將返回值格式化為JSON。 我使用這個(可能是非常類似新手的)代碼進行查詢;

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI
Imports System.Web.UI.WebControls

Partial Public Class SQLConnect
Inherits System.Web.UI.Page
'Defines SQL variables
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Dim ReadData As String
Dim i As Integer


Sub Click(ByVal s As Object, ByVal e As EventArgs)

    'Define SQL address, database, username and password
    con.ConnectionString = "Data Source=localhost\SQLEXPRESS;Initial Catalog=tempdb;User ID=tesst;Password=test"
    Try
        'Initialize connection
        con.Open()
        'Specify SQL query
        cmd = New SqlCommand("SELECT * FROM Member", con)
        'Execute query, dump result array into variable
        dr = cmd.ExecuteReader()
        messageLabel.Text = "<br />Connection established<br />"

        While (dr.Read)
            i = 0
            For i = 0 To dr.FieldCount - 1
                'Dump query results into a variable
                ReadData += dr.Item(i).ToString
            Next
        End While

        'Print query results
        messageLabel2.Text = ReadData
        'Close connection
        con.Close()
    Catch ex As Exception
        messageLabel.Text = "<br />Connection failed<br />"
    End Try


    End Sub
End Class

我一直在看這個 ,我很想看到使用這個類或任何其他好方法的一些代碼示例。

任何幫助將非常感謝,您可能有任何積分和提示。

你最好在MS的網站上看這個

JavaScriptSerializer類

它只是一個Serialize(你的對象)的情況

您可能會發現直接從數據(作為數據表/集而不是讀取器)直接轉到JSON更容易,例如Serialize(datatable)

並且還看看

James Newton King的JSON.NET庫

Rick Strahl - DataReader的JSON序列化

希望這可以幫助

使用JsonResult非常容易。 你可以從你的控制器中調用Json()方法,並將你傳遞給它的對象Json() ,然后給你一個JsonResult 所以這是一個簡單的例子,使用你的變量:

Public Class MyController
   Inherits Controller

   Public Function GetDataStuff As ActionResult
        ....
        ....
       Return Json(ReadData)
   End Function

End Class

是的你應該使用JavaScriptSerializer。 除了MS的幫助站點上的示例,您可以下載asp.net mvc源代碼並查看JsonResult是如何實現的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM