Dim objConnection
Dim objCommand
Dim objRecordset
Dim strConnectionString
Dim strSQL
Dim lngValue
Dim lngCount
strConnectionString = "Provider=MSDASQL;DSN=sampleDSN;UID=;PWD=;"
strSQL = "select from WINCC-DATA where ID=1"
Set objConnection = CreateObject("ADODB.Connection")
objConnection.ConnectionString = strConnectionString
objConnection.Open
Set objRecordset = CreateObject("ADODB.Recordset")
Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection
objCommand.CommandText = strSQL
Set objRecordset = objCommand.Execute
lngCount = objRecordset.Fields.Count
If (lngCount>0) Then
objRecordset.movefirst
lngValue = objRecordset.Fields(0).Value
HMIRuntime.Tags("b").Write lngValue
Else
HMIRuntime.Trace "Selection returned no fields" & vbNewLine
End If
Set objCommand = Nothing
objConnection.Close
Set objRecordset = Nothing
Set objConnection = Nothing
问题补充:
我是新手,最好能每条都解释出来,特别是HMIRuntime.Tags("b").Write lngValue这一句中是把lngValue = objRecordset.Fields(0).Value中具体什么值给b。谢谢
最佳答案
很简单,你要学点vbs和ado的知识就能看懂了。
今天俺闲来无事,就给你解释解释:(代码正确与否我就不管了)
strConnectionString = "Provider=MSDASQL;DSN=sampleDSN;UID=;PWD=;"
'连接数据库的字符串,后面用
strSQL = "select from WINCC-DATA where ID=1"
'查询数据库的字符串,后面用
Set objConnection = CreateObject("ADODB.Connection")
'创建ado对象
objConnection.ConnectionString = strConnectionString
'把前面的连接字符串赋值给创建好的ado对象
objConnection.Open
'连接数据库
Set objRecordset = CreateObject("ADODB.Recordset")
'创建recordset对象(记录集)
Set objCommand = CreateObject("ADODB.Command")
'创建command对象,这是用来执行查询等命令的
objCommand.ActiveConnection = objConnection
'command要跟连接的数据库“勾搭”一下啊
objCommand.CommandText = strSQL
Set objRecordset = objCommand.Execute
'执行前面的select语句去查记录
lngCount = objRecordset.Fields.Count
'得到查询记录的数量
If (lngCount>0) Then
'如果返回的记录数量大于0就....
objRecordset.movefirst
'指针移到第一条记录
lngValue = objRecordset.Fields(0).Value
'得到第一个字段的值
HMIRuntime.Tags("b").Write lngValue
'写到b这个tag中去
Else
'没查到记录就返回一条错误信息
HMIRuntime.Trace "Selection returned no fields" & vbNewLine
End If
'释放对象
Set objCommand = Nothing
objConnection.Close
Set objRecordset = Nothing
Set objConnection = Nothing
提问者对于答案的评价:
xiexie
原创文章,作者:more0621,如若转载,请注明出处:https://www.zhaoplc.com/plc270428.html