将Web服务连接到数据库并显示信息

时间:2015-05-15 09:50:35

标签: sql sql-server vb.net web-services

我是初学者VB.Net开发人员,想知道如何创建Web服务并将其连接到SQL 2012数据库并在表中显示项目。数据库表有几个字段,包括Stock Item,Manufacturer,Free Stock Quantity,Price等。

如果我添加断点并逐步执行代码,我可以看到一个值传递到记录集中的字符串并返回,但是,这不能正确显示。显然我已经更改了服务器,用户名和密码,但这就是下面显示的代码。

Public Class Service1
Inherits System.Web.Services.WebService

Private sqlconnection As ADODB.Connection

<WebMethod()> _
Public Function ShowStockItems() As String

    Dim Command As New SqlCommand

    sqlconnection = New ADODB.Connection
    sqlconnection.ConnectionString = "driver={SQL Server};server=server;uid=id;pwd=password;database=Able_Instruments"
    Try
        sqlconnection.Open()
        Dim strReturn As String = ""
        Dim rstStockItem As New ADODB.Recordset
        Dim strStockItem As String = "Select * from StockItem"
        rstStockItem.Open(strStockItem, sqlconnection)
        With rstStockItem
            If Not .BOF Then
                .MoveFirst()
                strReturn = .Fields.Item("TaxCodeID").Value
            End If![enter image description here][1]
        End With
        rstStockItem.Close()
        sqlconnection.Close()
        'Return strReturn
    Catch ex As Exception
    Finally
    End Try
End Function
End Class

我不确定问题是否明显,但我希望能够显示股票项目的ID和股票项目的名称。对于此示例,我使用TaxCodeID来确保代码正常工作。使用Visual Studio 2010,如果需要,还可以访问2013。

http://i.stack.imgur.com/KWJ14.png

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

当我不使用Entity Framework时,我喜欢为复杂的数据检索构建类。

Public Class StockItem
  Public Property Name As String
  Public Property ID As Integer
  'others as needed
End Class 

用法:

<WebMethod()> _
Public Function ShowStockItems() As StockItem
 Dim _stockItem As New StockItem
 Dim Command As New SqlCommand
 sqlconnection = New ADODB.Connection
 sqlconnection.ConnectionString = "driver={SQL Server};server=server;uid=id;pwd=password;database=Able_Instruments"
 Try
    sqlconnection.Open()
    Dim strReturn As String = ""
    Dim rstStockItem As New ADODB.Recordset
    Dim strStockItem As String = "Select * from StockItem"
    rstStockItem.Open(strStockItem, sqlconnection)
    With rstStockItem
        If Not .BOF Then
            .MoveFirst()
            _stockItem.ID = Convert.ToInt32(.Fields.Item("TaxCodeID").Value)
            _stockItem.Name = .Fields.Item("what field you need).Value
        End If
    End With
 Catch
 Finally
   rstStockItem.Close()
   sqlconnection.Close()
 End Try
 Return _stockItem
End Function