subscribe to our weekly newsletter to get notified with latest story and article Subscribe now!
tagdatabase
)."CREATE DATABASE tagdatabase2;"
INT
, NVARCHAR(50)
), and constraints (e.g., NOT NULL
, PRIMARY KEY
).Users
table:
USE tagdatabase2; -- Switch to the database
CREATE TABLE tagtable (
id INT PRIMARY KEY, -- Unique identifier
tagname NVARCHAR(50) NOT NULL, -- Tag name
tagvalue INT NOT NULL, -- Tag value
JoinDate DATE DEFAULT GETDATE() -- Default to current date
);
MySql
).conn
: The database connection object.strConn
: The connection string for the ODBC Data Source Name (DSN).sqlSelect
: The SQL query to retrieve the desired value.dsn
: The ODBC DSN name (e.g., "MySql").valueRead
: Holds the value retrieved from the database.textfield1
and textfield2
: References to text fields in the HMI runtime.HmiRuntime.Screens
object:
Set textfield1 = HmiRuntime.Screens("Screen_1").ScreenItems("Text field_1") Set textfield2 = HmiRuntime.Screens("Screen_1").ScreenItems("Text field_2")These text fields are used to display the results of the script.
dsn = "MySql" strConn = "DSN=" & dsn & ";Trusted_Connection=Yes;"The
Trusted_Connection=Yes
setting enables Windows Authentication.
tagname = 'temprature1'
:
sqlSelect = "SELECT tagvalue FROM tagtable WHERE tagname = 'temprature1'"
The script creates and opens the connection using the ADO object:
Set conn = CreateObject("ADODB.Connection") conn.Open strConnError handling is enabled using
On Error Resume Next
.
Set rs = conn.Execute(sqlSelect) If Not rs.EOF Then valueRead = rs.Fields("tagvalue").Value textfield1.Text = "Value retrieved: " & valueRead Else textfield2.Text = "No record found for tagname 'temprature1'." End IfIf the query returns a result, the value is displayed in
textfield1
. Otherwise, an error message is shown in textfield2
.
textfield2.Text = "Failed to connect to the database."All resources (recordset and connection) are closed and cleaned up at the end:
If conn.State = 1 Then conn.Close Set conn = Nothing
MySql
, tagtable
) with actual database and table details.