Example Configuring A Database Connection With VBS
Example Configuring A Database Connection With VBS
June 2018
Print this page Generate PDF
Entry type: Manual, Entry ID: 109736230, Entry date: 03/14/2016
WinCC V7.4 Scripting: VBS, ANSI-C, VBA
Document: ttttttt WinCC: Scripting (VBS, ANSI-C, VBA) (02/2016, English) ttttttt
Type of topic: ttttttt Example
Introduction
The following examples describe the configuration of an Access database link via an ODBC driver.
Procedure, Example 1
1. Create the Access database with the WINCC_DATA table and columns (ID, TagValue) with the ID as the Auto Value.
2. Set up the ODBC data source with the name "SampleDSN", reference to the above Access database.
3. Programming.
Example 1
'VBS108
Dim objConnection
Dim strConnectionString
Dim lngValue
Dim strSQL
Dim objCommand
strConnectionString = "Provider=MSDASQL;DSN=SampleDSN;UID=;PWD=;"
lngValue = HMIRuntime.Tags("Tag1").Read
strSQL = "INSERT INTO WINCC_DATA (TagValue) VALUES (" & lngValue & ");"
Set objConnection = CreateObject("ADODB.Connection")
objConnection.ConnectionString = strConnectionString
objConnection.Open
Set objCommand = CreateObject("ADODB.Command")
With objCommand
.ActiveConnection = objConnection
.CommandText = strSQL
End With
objCommand.Execute
Set objCommand = Nothing
objConnection.Close
Set objConnection = Nothing
Procedure, Example 2
Example 2
'VBS108a
Dim objConnection
Dim objCommand
Dim objRecordset
Dim strConnectionString
Dim strSQL
Dim lngValue
Dim lngCount
strConnectionString = "Provider=MSDASQL;DSN=SampleDSN;UID=;PWD=;"
strSQL = "select TagValue 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("dbValue").Write lngValue
Else
HMIRuntime.Trace "Selection returned no fields" & vbNewLine
End If
Set objCommand = Nothing
objConnection.Close
Set objRecordset = Nothing
Set objConnection = Nothing
There are several ways in which to define the ConnectionString for the connection depending on the provider used:
Microsoft OLE DB provider for ODBC
Enables connections to any ODBC data source. The corresponding syntax is:
"[Provider=MSDASQL;]{DSN=name|FileDSN=filename};
[DATABASE=database;]UID=user; PWD=password"
Other Microsoft OLE DB Providers (e.g. MS Jet, MS SQL Server)
It is possible to work without DSN. The corresponding syntax is:
"[Provider=provider;]DRIVER=driver; SERVER=server;
DATABASE=database; UID=user; PWD=password"
See also
General examples for VBScript