Sabtu, 05 Mei 2012

Web Service Database dengan VB.NET

Web Service - VB.NET 

Buat WebService dengan cara klik File - New - Web Site. Pilih ASP.NET Web Service. Pilih Language : Visual Basic.

Kemudian masukkan database, misalnya db.mdb ke direktori App_Data.

Tuliskan kode program berikut ini pada file App_Code/Service.vb :

Imports System.Data

Imports System.Data.OleDb

Imports System.Web

Imports System.Web.Services

Imports System.Web.Services.Protocols



' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

' <System.Web.Script.Services.ScriptService()> _

<WebService(Namespace:="http://tempuri.org/")> _

<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _

Public Class Service

Inherits System.Web.Services.WebService



'<WebMethod()> _

'Public Function HelloWorld() As String

' Return "Hello World"

'End Function



<WebMethod()> _

Public Function getTb() As DataSet

Dim cn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("~\App_Data") & "\db.mdb")

cn.Open()

Dim cm As OleDbCommand = New OleDbCommand("SELECT * FROM tb", cn)

Dim rd As OleDbDataReader = cm.ExecuteReader()

Dim ds = New DataSet

ds.Tables.Add(New DataTable("tb"))

ds.Load(rd, LoadOption.Upsert, ds.Tables("tb"))

Return ds

End Function



<WebMethod()> _

Public Function insertTb(ByVal id As String, ByVal nm As String, ByVal dsc As String, ByVal dt As String, ByVal prc As String) As String

Dim cn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("~\App_Data") & "\db.mdb")

cn.Open()

Dim cm As OleDbCommand = New OleDbCommand("INSERT INTO tb (id, nm, dsc, dt, prc) VALUES ('" + id + "', '" + nm + "', '" + dsc + "', #" + dt + "#, " + prc + ")", cn)

cm.ExecuteNonQuery()

Return "Succeed"

End Function



<WebMethod()> _

Public Function updateTb(ByVal id As String, ByVal nm As String, ByVal dsc As String, ByVal dt As String, ByVal prc As String) As String

Dim cn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("~\App_Data") & "\db.mdb")

cn.Open()

Dim cm As OleDbCommand = New OleDbCommand("UPDATE tb SET nm = '" + nm + "', dsc = '" + dsc + "', dt = #" + dt + "#, prc = " + prc + " WHERE id = '" + id + "'", cn)

cm.ExecuteNonQuery()

Return "Succeed"

End Function



<WebMethod()> _

Public Function deleteTb(ByVal id As String) As String

Dim cn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("~\App_Data") & "\db.mdb")

cn.Open()

Dim cm As OleDbCommand = New OleDbCommand("DELETE FROM tb WHERE id = '" + id + "'", cn)

cm.ExecuteNonQuery()

Return "Succeed"

End Function



End Class


Hasilnya dapat dilihat dengan cara klik Debug - Start Debugging (Run - F5)