【问题标题】:SQL queries through VB.NET and JSON通过 VB.NET 和 JSON 进行 SQL 查询
【发布时间】:2010-02-19 14:09:53
【问题描述】:

我对 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

我一直在看this,我很想看到一些使用这个类或任何其他好方法的代码示例。

非常感谢您提供任何帮助,以及您可能有的任何要点和提示。

【问题讨论】:

    标签: asp.net sql vb.net json


    【解决方案1】:

    您最好在 MS 的网站上查看此内容

    JavaScriptSerializer Class

    它只是一个Serialize(Your Object)的例子

    您可能会发现直接从数据(作为数据表/集合而不是读取器)直接转换为 JSON 更容易,例如 Serialize(datatable)

    也可以看看

    James Newton King's JSON.NET Library

    Rick Strahl - JSON Serialization of a DataReader

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      JsonResult 的使用非常简单。你可以从你的控制器调用Json()方法,它会将你传递给它的对象JSON化,并返回一个JsonResult。所以这是一个简单的例子,使用你的变量:

      Public Class MyController
         Inherits Controller
      
         Public Function GetDataStuff As ActionResult
              ....
              ....
             Return Json(ReadData)
         End Function
      
      End Class
      

      【讨论】:

        【解决方案3】:

        是的,你应该使用 JavaScriptSerializer。除了 MS 帮助站点上的示例,您还可以下载 asp.net mvc 源代码并查看 JsonResult 是如何实现的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-07-26
          • 1970-01-01
          • 2013-06-30
          • 2011-03-03
          • 2023-03-13
          • 1970-01-01
          • 2021-09-08
          相关资源
          最近更新 更多