VB.net连接SAP实例,vb.net写法

上一篇简单写了vb6.0中访问SAP, 本篇用vb.net实现同样的功能,只是把读取出来的内容存放在数据库中,然后利用GridView显示出来。 当然可以直接存入DataTable或DataSet中直接显示出来。

以下见代码示例:

Imports System

Imports System.Collections.Generic

Imports System.ComponentModel

Imports System.Data

Imports System.Drawing

Imports System.Text

Imports System.Windows.Forms

Imports System.Data.OleDb

Imports System.Xml

Public Class SAPConn

Public oFunction As Object ' SAP Functions

Public oConnection As Object ' SAP oConnection

Dim cmd As OleDbCommand

Dim SqlAd As OleDbDataAdapter

Dim sql As String

'测试连接的代码

Private Sub BtnConnn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnConnn.Click

Try

oFunction = CreateObject("SAP.Functions.unicode")

oConnection = oFunction.Connection

oConnection.User = "CRMDEV69"

oConnection.Password = "654321"

oConnection.System = "CD2"

oConnection.ApplicationServer = "172.18.95.173"

oConnection.SystemNumber = 7

oConnection.Client = "164"

oConnection.Language = "ZH"

If oConnection.Logon(0, True) = True Then

MsgBox("连接成功!")

Else

MsgBox("连接失败!")

End If

Catch ex As Exception

MsgBox(ex.ToString(), MsgBoxStyle.Information, "提示")

Return

End Try

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim GetCustomers As Object

Dim Customers As Object

Dim i As Integer

Dim sqlstr As String = ""

' 通过RFC接口远程运行SAP内部函数ZCSMS_GET_HRINFO

' 赋要调用的SAP内建函数名

Try

GetCustomers = oFunction.Add("ZCSMS_GET_HRINFO")

'设置输入参数并赋值

GetCustomers.Exports("BEGDAFROM") = ""

GetCustomers.Exports("BEGDATO") = ""

GetCustomers.Exports("MILL") = "7960"

GetCustomers.Exports("NUMBERFROM") = "0061500001"

GetCustomers.Exports("NUMBERTO") = "0061500200"

Customers = GetCustomers.Tables("THR")

If GetCustomers.Call Then

'循环插入到数据库表中

For i = 1 To Customers.RowCount

sqlstr = "Insert into ghy_employee(MILL, PERNR, NAME1, STEXT) values ('" & Customers(i, "MILL") & "','" & Customers(i, "PERNR") & "','" & Customers(i, "NAME1") & "','" & Customers(i, "STEXT") & "' )"

Config.ExecAccess(sqlstr)

Next i

MsgBox("获取数据成功")

Else

MsgBox(" 搜索出错! 出错信息: " + GetCustomers.exception)

End If

Catch ex As Exception

MsgBox(ex.ToString)

Return

End Try

End Sub

'通过GridView显示数据

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

sql = "select * from ghy_employee "

SqlAd = New OleDbDataAdapter(sql, oConn)

DS.Clear()

If DS.Tables.Contains("ghy_employee") Then

DS.Tables.Remove("ghy_employee")

End If

SqlAd.Fill(DS, "ghy_employee")

DvInvoice.DataSource = DS.Tables("ghy_employee").DefaultView

DvInvoice.Refresh()

DvInvoice.ClearSelection()

DvInvoice.Columns("MILL").HeaderText = "工厂"

DvInvoice.Columns("PERNR").HeaderText = "员工编号"

DvInvoice.Columns("NAME1").HeaderText = "员工姓名"

DvInvoice.Columns("STEXT").HeaderText = "员工部门"

End Sub

End Class

以上两种写法都是利用创建组件OCX的方式进行, 通过调用类的方法进行也可以实现。 缺点是中文无法正常显示。

下一篇文章将贴出C#的例子以研究。