我有一个Windows服务,只要OPC服务器(KepServer)的数据发生变化,就会插入数据库。当我从Windows 7的服务任务管理器手动启动服务时,该服务正确插入。但该服务仅在系统启动时启动时插入一行数据,而所需的行数必须为20.因为它是Windows服务,它很难调试,也没有给出任何错误。
jjag
操作系统:Windows 7; DB:SQL Server Express; Win服务:在管理员
下运行我的代码:
Protected Overrides Sub OnStart(ByVal args() As String)
' Add code here to start your service.
'Create a new OPC Server object
ConnectedOPCServer = New OPCServer
ConnectedOPCServer.Connect("KEPware.KEPServerEx.V5")
Try
' Add the group and set its update rate
ConnectedServerGroups = ConnectedOPCServer.OPCGroups
ConnectedGroup = ConnectedServerGroups.Add("Test1")
Catch ex As Exception
' Error handling
End Try
' Set the update rate for the group
ConnectedGroup.UpdateRate = 400
' Subscribe the group so that you will be able to get the data change
' callbacks from the server
ConnectedGroup.IsSubscribed = True
ItemCount = 3
OPCItemIDs(1) = "Channel2.Device1.EndDate"
OPCItemIDs(2) = "Channel2.Device1.Material"
OPCItemIDs(3) = "Channel2.Device1.BatchSchedule"
ClientHandles(1) = 1
ClientHandles(2) = 2
ClientHandles(3) = 3
Try
' Establish a connection to the OPC item interface of the connected group
OPCItemCollection = ConnectedGroup.OPCItems
OPCItemCollection.DefaultIsActive = True
OPCItemCollection.AddItems(ItemCount, OPCItemIDs, ClientHandles, ItemServerHandles, ItemServerErrors)
Catch ex As Exception
' Error handling
End Try
EventLog1.WriteEntry("In OnStart")
End Sub
Public Sub ConnectedGroup_DataChange(ByVal TransactionID As Integer, ByVal NumItems As Integer, ByRef ClientHandles As System.Array, ByRef ItemValues As System.Array, ByRef Qualities As System.Array, ByRef TimeStamps As System.Array) Handles ConnectedGroup.DataChange
'This is my sub which inserts into database in the event of data change from OPC Server
Const NoOfItems = 3
Dim ObjOPCItem As OPCAutomation.OPCItem
Dim Array_Values(NoOfItems) As Object
For Each ObjOPCItem In OPCItemCollection
Array_Values(ObjOPCItem.ClientHandle) = ObjOPCItem.Value
Next
ObjOPCItem = Nothing
Dim sql As String
sql = "INSERT INTO BatchReport (BatchCode,BatchNumber)VALUES(@AV,@AVa);"
If Array_Values(3) < 20 Then
Try
connection.Open()
dataadapter.InsertCommand = New SqlCommand(sql, connection)
dataadapter.InsertCommand.Parameters.Add("@AV", SqlDbType.Int, 4).Value = Array_Values(1)
dataadapter.InsertCommand.Parameters.Add("@AVa", SqlDbType.Int, 4).Value = Array_Values(3)
dataadapter.InsertCommand.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
connection.Close()
End If
End Sub