0% found this document useful (0 votes)
93 views

Manual

The document discusses the SQL4automation connector, which allows connecting automation systems like CODESYS to SQL databases. It describes how to install and configure the connector, set up data sources, and use the target libraries for different automation systems including CODESYS V2.3, CODESYS V3, and Beckhoff TwinCAT V2. The document provides requirements, instructions for function blocks, global variables, and sample projects for each supported target system.

Uploaded by

Aynen JohnWaynen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
93 views

Manual

The document discusses the SQL4automation connector, which allows connecting automation systems like CODESYS to SQL databases. It describes how to install and configure the connector, set up data sources, and use the target libraries for different automation systems including CODESYS V2.3, CODESYS V3, and Beckhoff TwinCAT V2. The document provides requirements, instructions for function blocks, global variables, and sample projects for each supported target system.

Uploaded by

Aynen JohnWaynen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 208

Contents

1 SQL4automation ......................................................................................................................................... 9
2 SQL4automation Connector ..................................................................................................................... 10
2.1 Requirements ................................................................................................................................... 10
2.2 Topology ........................................................................................................................................... 10
2.2.1 Stand-Alone System ................................................................................................................. 10
2.2.2 Separate SQL-Server ................................................................................................................ 11
2.2.3 Separate Automation and Data Network (e.g. Company Network) ........................................ 11
2.3 Installation ........................................................................................................................................ 12
2.3.1 Windows .................................................................................................................................. 12
2.3.2 Linux (Ubuntu) ......................................................................................................................... 12
3 Configuration SQL4automation Connector .............................................................................................. 13
3.1 Config Tool ........................................................................................................................................ 13
3.2 Connecting to the Connector............................................................................................................ 13
3.3 Installing a new Host and Connecting to the Connector .................................................................. 14
3.4 Main Window Config Tool ................................................................................................................ 16
3.5 Configuration .................................................................................................................................... 17
3.6 Error-Reset ........................................................................................................................................ 18
3.7 Setting up the firewall ...................................................................................................................... 19
3.7.1 Create a new rule for a program .............................................................................................. 20
3.7.2 Define a new rule for one or several ports .............................................................................. 21
3.7.3 Further firewall rules................................................................................................................ 21
3.8 Logfile Options .................................................................................................................................. 22
3.9 Demo-Mode ...................................................................................................................................... 22
3.10 Licensing ........................................................................................................................................... 22
3.10.1 License Dongle ......................................................................................................................... 22
3.10.2 Software License ...................................................................................................................... 22
3.11 Debugger .......................................................................................................................................... 24
3.11.1 General ..................................................................................................................................... 24
3.11.2 Debugger Options .................................................................................................................... 24
3.11.3 Display Settings Debugger ....................................................................................................... 25
3.12 Query Tool ........................................................................................................................................ 26
4 Data Sources ............................................................................................................................................. 27
4.1 Data Scources under Windows (ODBC) ............................................................................................ 27
4.1.1 ODBC Data Source Administrator ............................................................................................ 27

2/208
4.1.1 Setting up the connection to the test database ...................................................................... 28
4.1.2 Transferring settings to the SQL4automation Connector ........................................................ 30
4.2 Data Sources under Linux ................................................................................................................. 31
4.2.1 ODBC under Linux .................................................................................................................... 31
4.2.2 Direct Database Connection under Linux ................................................................................ 34
5 Target-Libraries ......................................................................................................................................... 36
5.1 CODESYS V2.3 / SQL4CODESYS – Target: „Standard“ ....................................................................... 36
5.1.1 Requirements ........................................................................................................................... 36
5.1.2 Function Block .......................................................................................................................... 36
5.1.3 Global Constants ...................................................................................................................... 36
5.1.4 Global Variables ....................................................................................................................... 37
5.1.5 Instance / Interface .................................................................................................................. 38
5.1.6 Handshake................................................................................................................................ 39
5.1.7 Error Codes Return-Value ........................................................................................................ 39
5.1.8 Sample Project SQL4CoDeSysSample ...................................................................................... 40
5.2 CODESYS V3 / SQL4CODESYSV3 – Target: „Standard“ ...................................................................... 42
5.2.1 Requirements ........................................................................................................................... 42
5.2.2 Installing the library ................................................................................................................. 42
5.2.3 Function Block .......................................................................................................................... 42
5.2.4 Global Constants ...................................................................................................................... 42
5.2.5 Global Variables ....................................................................................................................... 43
5.2.6 Instance / Interface .................................................................................................................. 43
5.2.7 Handshake................................................................................................................................ 44
5.2.8 Error Codes Return-Value ........................................................................................................ 44
5.2.9 Sample Project SQL4CoDeSysV3_Sample.project .................................................................... 45
5.3 Beckhoff TwinCAT V2 / SQL4TwinCAT – Target: „Standard“ ............................................................ 47
5.3.1 Requirements ........................................................................................................................... 47
5.3.2 Function Block .......................................................................................................................... 47
5.3.3 Global Constants ...................................................................................................................... 47
5.3.4 Global Variables ....................................................................................................................... 48
5.3.5 Instance / Interface .................................................................................................................. 49
5.3.6 Handshake................................................................................................................................ 50
5.3.7 Error Codes Return-Value ........................................................................................................ 50
5.3.8 Sample Project SQL4TwinCATSample ...................................................................................... 51
5.4 Beckhoff TwinCAT V3 / SQL4TwinCAT3 – Target: „Standard“ .......................................................... 53
5.4.1 Requirements ........................................................................................................................... 53

3/208
5.4.2 Function Block .......................................................................................................................... 53
5.4.3 Global Constants ...................................................................................................................... 53
5.4.4 Global Variables ....................................................................................................................... 54
5.4.5 Instance / Interface .................................................................................................................. 54
5.4.6 Handshake................................................................................................................................ 55
5.4.7 Error Codes Return-Value ........................................................................................................ 55
5.4.8 Sample Project SQL4TwinCAT3 Sample program .................................................................... 56
5.5 Stäubli VAL3 / SQL4Val3 – Target: „Staeubli Val3“ ........................................................................... 58
5.5.1 Requirements ........................................................................................................................... 58
5.5.2 Instance / Interface .................................................................................................................. 58
5.5.3 Creating the Socket .................................................................................................................. 59
5.5.4 Integrating the Library and user-defined Data Types into Val3 Project ................................... 60
5.5.5 Sample Project SQL4Val3Sample ............................................................................................. 61
5.5.6 Error Codes Return-Value ........................................................................................................ 61
5.6 S7-1200 / S7-1500 TIA13 StringTable / SQL4Siemens – Target: “Siemens S7” ................................. 62
5.6.1 Requirements ........................................................................................................................... 62
5.6.2 Data modules ........................................................................................................................... 64
5.6.3 Data types (UDT) ...................................................................................................................... 64
5.6.4 Auxiliary functions.................................................................................................................... 64
5.6.5 Data area .................................................................................................................................. 66
5.6.6 Configuration of the Connector ............................................................................................... 67
5.6.7 Ethernet interface settings ...................................................................................................... 68
5.6.8 The sample project................................................................................................................... 69
5.6.9 Error codes Return-Value ......................................................................................................... 72
5.7 S7-1200 / S7-1500 TIA13 DataBuffer / SQL4Siemens – Target: „Siemens S7“ ................................. 73
5.7.1 Requirements ........................................................................................................................... 73
5.7.2 Data modules ........................................................................................................................... 75
5.7.3 Data types (UDT) ...................................................................................................................... 75
5.7.4 Auxiliary functions.................................................................................................................... 75
5.7.5 Data area .................................................................................................................................. 77
5.7.6 Configuration of the Connector ............................................................................................... 78
5.7.7 Ethernet interface settings ...................................................................................................... 79
5.7.8 The sample project................................................................................................................... 80
5.7.9 Error codes Return-Value ......................................................................................................... 83
5.8 S7-300 PN/DP, IM151-8, WinAC RTX TIA13 / SQL4Siemens – Target: „Siemens S7“ ....................... 84
5.8.1 Requirements ........................................................................................................................... 84

4/208
5.8.2 Data modules ........................................................................................................................... 86
5.8.3 Data types (UDT) ...................................................................................................................... 86
5.8.4 Auxiliary functions.................................................................................................................... 87
5.8.5 Data area .................................................................................................................................. 88
5.8.6 Configuration of the Connector ............................................................................................... 89
5.8.7 Ethernet interface settings ...................................................................................................... 90
5.8.8 The sample project................................................................................................................... 91
5.8.9 Error codes Return-Value ......................................................................................................... 94
5.9 S7-300 CP-343 TIA13 / SQL4Siemens – Target: „Siemens S7“ .......................................................... 95
5.9.1 Requirements ........................................................................................................................... 95
5.9.2 Data modules ........................................................................................................................... 96
5.9.3 Data types (UDT) ...................................................................................................................... 96
5.9.4 Setting of the IP address of the CPs ......................................................................................... 98
5.9.5 Adding a new network connection .......................................................................................... 98
5.9.6 Auxiliary functions.................................................................................................................. 100
5.9.7 Data area ................................................................................................................................ 102
5.9.8 Configuration of the Connector ............................................................................................. 103
5.9.9 Ethernet interface settings .................................................................................................... 104
5.9.10 The sample project................................................................................................................. 105
5.9.11 Error codes Return-Value ....................................................................................................... 108
5.10 S7-300 PN/DP, IM151-8, WinAC RTX SIMATIC Manager ST / SQL4Siemens – Target: „Siemens S7“
109
5.10.1 Requirements ......................................................................................................................... 109
5.10.2 Data modules ......................................................................................................................... 111
5.10.3 Data types (UDT) .................................................................................................................... 111
5.10.4 Auxiliary functions.................................................................................................................. 112
5.10.5 Data area ................................................................................................................................ 113
5.10.6 Configuration of the Connector ............................................................................................. 114
5.10.7 Ethernet interface settings .................................................................................................... 115
5.10.8 Changing of the block address ............................................................................................... 116
5.10.9 The sample project................................................................................................................. 118
5.10.10 Error codes Return-Value ....................................................................................................... 120
5.11 S7-300 CP-343 SIMATIC Manager ST / SQL4Siemens – Target: „Siemens S7“................................ 121
5.11.1 Requirements ......................................................................................................................... 121
5.11.2 Data modules ......................................................................................................................... 122
5.11.3 Data types (UDT) .................................................................................................................... 122

5/208
5.11.4 Setting of the IP address of the CPs ....................................................................................... 123
5.11.5 Adding of a new network connection .................................................................................... 124
5.11.6 Hilfsfunktionen ....................................................................................................................... 126
5.11.7 Data area ................................................................................................................................ 127
5.11.8 Configuration of the Connector ............................................................................................. 128
5.11.9 Settings of the ethernet port ................................................................................................. 129
5.11.10 Changing of the block addresses ............................................................................................ 130
5.11.11 The sample project................................................................................................................. 132
5.11.12 Error codes Return-Value ....................................................................................................... 134
5.12 S7-300 PN/DP, IM151-8, WinAC RTX SIMATIC Manager IL, Ladder/ SQL4Siemens – Target:
„Siemens S7“ ............................................................................................................................................... 135
5.12.1 Requirements ......................................................................................................................... 135
5.12.2 Function Block (FB) ................................................................................................................ 136
5.12.3 Data Blocks (DB) ..................................................................................................................... 137
5.12.4 Data Types (UDT) ................................................................................................................... 138
5.12.5 Data Region ............................................................................................................................ 139
5.12.6 Table of Symbols .................................................................................................................... 140
5.12.7 Ethernet-Interface Settings .................................................................................................... 141
5.12.8 Configuring the Connector ..................................................................................................... 142
5.12.9 Sample Project ....................................................................................................................... 143
5.12.10 Error Codes Return-Value ...................................................................................................... 152
5.12.11 Status of Error Number 41 ..................................................................................................... 153
5.12.12 Status of Error Number 51 ..................................................................................................... 154
5.12.13 Status of Error Number 61 ..................................................................................................... 155
5.12.14 Status of Error Number 71 ..................................................................................................... 156
5.13 S7-300 mit CP343 / SQL4Siemens SIMATIC Manager IL, Ladder – Target: “Siemens S7”............... 157
5.13.1 Requirements ......................................................................................................................... 157
5.13.2 Function Block (FB) ................................................................................................................ 158
5.13.3 Data Blocks (DB) ..................................................................................................................... 159
5.13.4 Data Types (UDT) ................................................................................................................... 160
5.13.5 Data Region ............................................................................................................................ 161
5.13.6 Table of Symbols .................................................................................................................... 162
5.13.7 Ethernet-Interface Settings .................................................................................................... 163
5.13.8 Configuring the Connector ..................................................................................................... 165
5.13.9 Sample Project ....................................................................................................................... 166
5.13.10 Error Codes Return-Value ...................................................................................................... 175

6/208
5.13.11 Status of Error Number 41 ..................................................................................................... 176
5.13.12 Status of Error Number 51 ..................................................................................................... 177
5.13.13 Status of Error Number 61 ..................................................................................................... 178
5.13.14 Status of Error Number 71 ..................................................................................................... 179
5.14 SQL4Siemens / S7-400 CP443 SIMATIC Manager IL, Ladder – Target: “Siemens S7” .................... 180
5.15 Allen Bradley, Rockwell / SQL4RSLogix – Target: „Standard“ ......................................................... 181
5.15.1 Requirements ......................................................................................................................... 181
5.15.2 Importing Add-On and Tags ................................................................................................... 181
5.15.3 Add-On (Function Block) ........................................................................................................ 181
5.15.4 Data Types.............................................................................................................................. 182
5.15.5 Tags ........................................................................................................................................ 185
5.15.6 Parameters SQL4automation Function Block ........................................................................ 187
5.15.7 Handshake.............................................................................................................................. 188
5.15.8 Error Codes Return-Value ...................................................................................................... 188
5.15.9 Sample Project ....................................................................................................................... 189
5.16 Sigmatek / SQL4LASAL – Target: “Standard“ / “UTF16” ................................................................. 191
5.16.1 Requirements ......................................................................................................................... 191
5.16.2 The classes ............................................................................................................................. 191
5.16.3 Servers ................................................................................................................................... 192
5.16.4 Methods ................................................................................................................................. 192
5.16.5 Sample project SQL4LASALSample ........................................................................................ 193
5.17 ABB AC500 / SQL4AC500 – Target: “Standard” .............................................................................. 195
5.18 ABB Robotics / SQL4Rapid – Target: “Standard” ............................................................................ 196
5.18.1 Requirements ......................................................................................................................... 196
5.18.2 Variables to be defined .......................................................................................................... 196
5.18.3 Executing the Sample Project ................................................................................................ 197
5.19 KUKA / SQL4KUKA – Target: “KUKA” .............................................................................................. 199
5.19.1 Requirements ......................................................................................................................... 199
5.19.2 Installing the Interface ........................................................................................................... 199
5.19.3 Help Functions SQL4KUKA ..................................................................................................... 201
5.20 B&R / SQL4BR – Target: “Standard” ............................................................................................... 202
5.20.1 Requirements ......................................................................................................................... 202
5.20.2 Implementing the Library into the B&R Automation Studio .................................................. 202
5.20.3 Integrating the SQL4BR Library into the Application Program .............................................. 202
5.20.4 Global Variables ..................................................................................................................... 202
5.20.5 Instance / Interface ................................................................................................................ 202

7/208
5.20.6 Creating an Instance .............................................................................................................. 203
5.20.7 Error Codes Return-Value ...................................................................................................... 203
5.20.8 Sample Project SQL4BRSample .............................................................................................. 204
6 TLP – Target-Link-Protocol ...................................................................................................................... 205
6.1 Standard Protocol ........................................................................................................................... 205
6.1.1 Request to the Connector ...................................................................................................... 205
6.1.2 Response from the Connector ............................................................................................... 206
6.1.3 Error Codes Return-Value ...................................................................................................... 207
6.1.4 Handshake.............................................................................................................................. 208

8/208
1 SQL4automation

SQL4automation is a software solution for industrial use featuring the Connector at its core, which connects
the PLC and robot controls directly to your databases.
The Connector can be installed on your existing hardware, but it is also available as a pre-installed package on
an IPC.
With the Connector, industrial control systems can directly access SQL databases. Via SQL commands
[Structured Query Language], control systems can retrieve data from tables, insert data into tables, modify
data and delete it. Moreover, individual procedures can be executed by the databases. An OPC server is no
longer required. This improves performance and enhances security and flexibility.
Project-specific adjustments to the Connector are not necessary, as everything is programmed in the control
system. For many controls systems, there are ready-to-use libraries which can be integrated into your project
in no time.
The SQL4automation Connector satisfies the most demanding requirements in terms of reliability and
performance. Since 2007, it has continuously undergone further development and optimization. We have
utilized our experience and lessons learned from many applications for these improvements.

9/208
2 SQL4automation Connector
2.1 Requirements
The SQL4automation Connector V3 runs as a service on Windows (XP and up) or Linux (Ubuntu).
The connection between PLC / robot control and the Connector is established via TCP/IP. The connection to
the database is made via ODBC. This means control system, connector and database must be able to
communicate with each other via TCP/IP.

2.2 Topology
There are several options for arranging the connector and the database. See some installation possibilities
below:

SQL4automation Connector

Control (PLC, robot controls, ...)

SQL database

2.2.1 Stand-Alone System

Control system, SQL server and the SQL4automation Connector are installed on a PC or Control Panel-PC.

Control Panel-PC
Control
Control
SQL database SQL database
SQL4automation Connector SQL4automation Connector

Example 1 Example 2

10/208
2.2.2 Separate SQL-Server
The SQL server and the SQL4automation Connector are installed on a PC or Control Panel-PC.

SQL database Control Panel-PC


SQL4automation Connector SQL database
SQL4automation Connector

Maschinen-Netzwerk (Ethernet) Maschinen-Netzwerk (Ethernet)

Control Control

Example 3 Example 4

2.2.3 Separate Automation and Data Network (e.g. Company Network)

The SQL server is installed on a PC (e.g. Linux server) and connected to the data network. The control system
is connected to the automation network. The SQL4automation Connector is installed on a second PC or
Control Panel-PC. The connector interlinks both networks with each other. The networks can be protected
with a firewall.

Network database

Firmen-Netzwerk

Control Panel-PC
Machine database SQL4automation Connector

Maschinen-Netzwerk (Ethernet)

Control 1 Control 2 Control...


(PLC) (Robot control)

Example 5

11/208
2.3 Installation

2.3.1 Windows

Run the setup with administrator rights. Follow the installation instructions.
In order to license the Connector, the Sentinel licensing driver is installed along with the Connector, Config
Tool, Query Tool and Debugger.

2.3.2 Linux (Ubuntu)

In Linux, SQL4automation is installed via Terminal. All files required for installation are contained in the
Setup_S4A_Linux.zip file. Administrator rights are required for installation. The following scripts are required
for installation and deinstallation:
 S4AConnector-inst Installs the SQL4automation Connector.
 S4ATools-inst Installs the SQL4automation Tools: S4AConfig, S4ADebugger and
S4AQueryTool.
 S4AConnector-uninst Deinstalls the SQL4automation Connector.
 S4ATools-uninst Deinstalls the SQL4automation Tools: S4AConfig, S4ADebugger
and S4AQueryTool.
 Sentinel-uninst Deinstallis the Sentinel LDK driver. Caution, only execute
if no other program requires Sentinel LDK.

12/208
3 Configuration SQL4automation Connector
3.1 Config Tool
The Config Tool is used for the configuration of the SQL4automation Connector. The connection between
Config Tool and Connector is established via TCP/IP. If the Config Tool and Connector are located on the same
PC, the connection can be established via localhost. Otherwise a new host must be created.

3.2 Connecting to the Connector


If the Connector and Query Tool are located on the same PC, the connection can be established instantly by
clicking the “Connect” button.

13/208
3.3 Installing a new Host and Connecting to the Connector

By clicking the “Hosts” button, a new host can be created.

A name and an IP address can be assigned to the connection.

14/208
The connection to the Connector is established by clicking the “Connect” button.

15/208
3.4 Main Window Config Tool
In the main window of the Config Tool, the individual connections, the so-called links, are displayed on the
left-hand side. Each link connects a control system with a database. An individual control system can also
utilize several links.
On the right-hand side, information about the individual links is displayed.

The LED displays the status of each link.


The link can have the following statuses (even visible if it is not selected):
Purple The link is configured, but no valid license is present and the test license is not active
Red The link is configured, but not available yet (establishing the connection to the database or
error is pending).
Green The link is ready for connection
Blue The link is active and connected to a control system
Grey The link is establishing or terminating a connection

16/208
The link settings can be changed with “Set”, “Reset” resets an exisiting connection. Further, it can be
configured which message types are logged in the Debugger for each link. The following can be selected:
 Errors Only Error Messages
 Warnings Error Messages and Warnings
 Queries Error Messages, Warnings and all Queries
By clicking the “New” button, new connections can be created, clicking “Delete” deletes existing connections.
Clicking “Test” tests new connections. “Deactivate” deactivates a connection.

3.5 Configuration
The configuration tool is opened by clicking the “Set” button of the respective link.

For each link, the following settings are saved:

17/208
Link name
Description of the link
Target
Target type Type of control system. For most control systems, the setting “Standard” is used. For
Stäubli, Siemens, KUKA and UTF-16 control systems, the respective settings must be used.
Target IP Only an authorized control system is permitted to connect to the link. The control system is
identified via its IP. If the field is left empty, the IP of the control system which connects to
the link first is saved. After that, only this particular control system is able to communicate
with this particular link.
Connector
Connector IP IP address or host name under which the link is available
Connector Port Port number to the link
Timeout Timeout in seconds. If a query has not been executed completely after this time period, and
the connection is not closed by the control system, the query is reversed, the connection to
the control system is terminated and the port is automatically reopened.
Database
Datasource Data source name from the ODBC Data Source Administrator
User Id User name for connection establishment to the SQL server
Password Password for the user name
Creating a DSN is described under Capture 4, Data Sources.
UID and PWD are assigned and administered in the SQL server.
[ODBC Admin…] starts the ODBC Datensource Administrator

By clicking [OK], all changes are applied and the link is restarted.
(Additional information about ODBC configuration can be found below in the section ODBC data sources)

3.6 Error-Reset
A corrupt link can be reset by clicking the “Reset” button of the respective link. The connection to the PLC is
terminated, and the connection to the database is closed and reopened.

18/208
3.7 Setting up the firewall
The inquiries between control and connector are often blocked by the firewall. It is described here, how a
new rule is added to the firewall to allow connections to the connector. The example is explained on the basis
of the Windows firewall.
Open the firewall settings on the PC on which the SQL4automation connector is installed. For Windows 7,
these are under Start, Control Panel, System and Security, Windows Firewall:

Under the Advanced Settings new rules can be added.

Add a new inbound rule.

You can either add a program here or enable single ports.

19/208
3.7.1 Create a new rule for a program

If a firewall rule is created for a program, any connections to this program can be enabled.

Select the SQL4automation.exe in the SQL4automation installation path.

Allow connections. Allow in all networks. Afterwards an appropriate name has to be assigned to the rule and
the rule has to be saved.

20/208
3.7.2 Define a new rule for one or several ports
It is also possible to create firewall rules for one or several ports.

Enter the respective port or ports.

Allow connections. Allow in all networks. Afterwards an appropriate name has to be assigned to the rule and
the rule has to be saved.

3.7.3 Further firewall rules

Please note that the connection between the connector and the database can be blocked by firewalls as well,
if the connector and the database are not located on the same computer.
For this purpose, please contact your network administrator.

21/208
3.8 Logfile Options
Under Options, Logging… the logfile options of the connector (if connected) and the Config Tool can be set.

In doing so, it can be selected whether messages should be written into a logfile or to the console.
Please note: Writing into a logfile may block or crash your PC, because the size of the logfiles is growing
with every entry and the size of the logfiles cannot be monitored. Writing into a logfile is only
recommended for debugging over a short period of time.

3.9 Demo-Mode
Without a valid license, the Connector can be tested in its full functionality for 2 hours. The test license is
activated via [License, Activate Test license]. Upon expiry, the test license can be reactivated.

3.10 Licensing
Two kinds of license types are available. On the one hand the license dongle, and the software license on the
other.

3.10.1 License Dongle

The license dongle is the standard license of SQL4automation V3. Its advantage lies in easy transfer of the
license from one PC to another. For example, if one PC is used for testing purposes, and a different one is
used later on at the production line, the license can be easily transferred. Also exchanging the hard disk as a
consequence of service and maintenance does not pose any problems. The license is located on an external
hardware dongle.
The license on a dongle can be updated. Via [License - Get License Update File] a *.c2v file is created. This file
must be sent by the customer to [email protected]. After that, the customer receives a *.v2c file,
which is loaded onto the dongle via [License - Insert License Key].
Caution: The license is always updated on the Connector which is connected to the Config Tool.
This means that the license can be updated via network. The customer bears the sole responsibility that
the license is updated on the correct Connector, and that the dongle is not disconnected during the writing
process, or the connection between Config Tool and Connector is interrupted.

3.10.2 Software License


The software license should only be used if the use of a license dongle is not possible.

22/208
Caution: A software license cannot be transferred from one PC to another.
A software license can be obtained as follows: Via [License - Get Hardware Fingerprint] a *.c2v file is created.
This file must be sent by the customer to [email protected]. After that, the customer receives a
*.v2c file which is loaded onto the Connector via [License - Insert License Key].
The software license can be updated. Via [License - Get License Update File] a *.c2v file is created. This file
must be sent by the customer to [email protected]. After that, the customer receives a *.v2c file
which is loaded onto the Connector via [License - Insert License Key].
Caution: The license is always updated on the Connector which is connected to the Config Tool. This means
that the license can be updated via network. The customer bears the sole responsibility that the license is
updated on the correct Connector, and that the connection between Config Tool and Connector is not
interrupted during the update.

23/208
3.11 Debugger

3.11.1 General

The Debugger is launched via [Tools – S4ADebugger]. By clicking the “Connect” button, the Debugger
connects to the Connector which is selected in the Combo box.
It displays all queries which are made via each individual link. The verbosity of the debug messages of the
individual links which are logged is determined by the debug setting of the link. How this setting is changed is
described under 1 SQL4automation. Successful queries are displayed in black, errors in red and warnings in
blue text colour.
By clicking [Refresh], the displayed list is refreshed.
By clicking [Clear database] all existing entries in the Debugger are deleted.
By checking the options Auto-Scroll and Auto-Refresh, the display behaviour of the Debugger can be
determined.

3.11.2 Debugger Options

In the Config Tool, the Debugger options can be configured under [Options – Debugger].

Storage type: Determines the location for storing the Debug database. Setting the storage type
to Memory stores the Debug database in RAM, setting it to File stores it on the
hard disk drive. While storage in RAM has its advantage in speed, storage on hard
disk will prevent the data from loss upon restarting of the PC or the Connector.
I must be noted that having the setting on File will engage the hard disk drive

24/208
during each access to the Debug database. Depending on the type of hard disk
drive, this can be detrimental to the lifetime of the hard disk. For this reason,
the default setting for the storage location is Memory.
Maximum size (entries) Determines the maximum number of stored debug entries.
Max. Debug Level Determines the maximum debug level which is logged across all links,
independent from the individual setting of each link.

3.11.3 Display Settings Debugger


By clicking the [Selection] button, the display settings of the Debugger can be changed. The following
selection will appear:

Link selection Here, the links are selected for display.


Field selection Here, the type of information which is displayed about the individual links can be
selected.
Time selection Restricts the time period of the queries which are displayed.

25/208
3.12 Query Tool
The Query Tool is launched via [Tools – S4AQueryTool]. This tool is used to simulate the control system and
to test both the SQL queries and the links.

Under Host, the connection to the Connector is selected. The Port setting determines the port number of the
link which is used to establish the connection. The Target type must correspond with the Target type of the
link.
With the buttons “SELECT”, “INSERT”, “UPDATE” and “DELETE”, standard SQL strings can be copied into the
command window. These strings can then be modified and executed by clicking the “Send” button.
The SQL string can be copied from the window by pressing “Ctrl+C”.

Some connections require an extra authentication, which can be activated via the checkbox Authentication.

26/208
4 Data Sources
Generally, under Windows the connection to the database is realized via ODBC. As a consequence, all SQL
databases can be used. Especially in the case of Linux, direct database connections to a few selected
databases can also be established.

4.1 Data Scources under Windows (ODBC)


ODBC data sources (Open Database Connectivity) facilitate access to data from a wide range of database
administration systems. For the 32bit installation of SQL4automation the 32bit ODBC driver is used, for the
64bit version the 64bit ODBC driver is used.

4.1.1 ODBC Data Source Administrator


With the ODBC Data Source Administrator, the connections to the SQL server are configured. There are
several ways of launching the ODBC Data Source Administrator:
Config Tool
In the Config Tool, the ODBC Data Source Administrator can be launched under the link settings or via [Tools
– ODBC Admin]. The correct ODBC administrator is automatically started here.

Windows
The ODBC data source administrator can be started in the start menu using the run dialog with the command
line [ODBCAD32.exe] (32bit) or under [Start – System and Security – Administration] (32bit or 64bit
depending on the operating system).

To be able to use the ODBC connestion in the SQL4automation Connector, the connection must be
configured under System-DSN. A new connection can be created by clicking the “Add” button.
Depending on the database connector, the configuration windows have a different appearance. With every
configuration, a specific name is assigned (DSN Data Source Name). The SQL server is indicated with the Host
name or the IP address, in the case of MS Access databases simply the *.mdb file is selected, and the target
database to the SQL server is defined. In order to test the connection to the database, the user name and
password must be entered. Afterwards, these entries will be deleted, as the user name and password will be

27/208
stored in the SQL4automation Connector. In this way, unauthorized access to the database by third parties is
prevented. The MS Access Database does not support secure access with user and password.

MySQL Microsoft SQL Server 2005

MS Access

The saved settings are used by the SQL4automation Connector through the Data Source Name.

4.1.1 Setting up the connection to the test database

If the 32bit version of the SQL4automation connector has been installed the Access database can be used as
test database.
In case the 64bit version of the SQL4automation connector has been installed, the 64bit SQLite ODBC driver
has to be downloaded from the SQLite homepage and to be installed. Microsoft does not provide a 64bit
ODBC driver for the access database.

4.1.1.1 32bit installation of SQL4automation


To set up the connection to the test database, please start the ODBC Administrator from the Config Tool and
add a new system DSN as described in 4.1.1 ODBC Data Source Administrator.
Select the Microsoft Access driver (*.mdb).

28/208
Choose an appropriate name for your connection:

You may select the test database S4A-Test_DB.mdb via “select”. The S4A_Test_DB.mdb is located in the
installation directory of the SQL4automation Connectors.

29/208
4.1.1.2 64bit installation of SQL4automation
In order to set up the connection to the test database, start the ODBC administrator out of the Config Tool
and add a new system DSN as described in 4.1.1. ODBC Data Source Administrator.
Select the SQLite3 ODBC driver.

Choose an appropriate name for the ODBC connection and select the test database in the installation
directory of the SQL4automation connector.

4.1.2 Transferring settings to the SQL4automation Connector


As described under 3.5 Configuration, the connection is configured in the SQL4automation Connector. The
created DSN may be selected and the user name and password may be entered.

30/208
4.2 Data Sources under Linux
Just as under Windows, the connection of the databases via ODBC is also available under Linux. However,
since only a few free OBC drivers are available under Linux, also the direct connection of the most common
databases was implemented. The several database connections must first be installed under Linux. ODBC and
the direct connections to MySQL, PostgreSQL and TDS are provided directly by the package management
software of Linux. For installation, the scripts in the Plugins folder of Setup_S4A_Linux.zip can be executed.

4.2.1 ODBC under Linux

Under Linux, a connection to a database can be established via ODBC. Since a free ODBC driver for
connection to a Microsoft SQL Server is available, the procedure is explained by taking this connection as an
example.
This guide describes how a connection from a Linux to a MS SQL Server can be established via ODBC. One
computer is running the SQL4automation Connector under Ubuntu, the other computer a Microsoft SQL
Server on a Windows platform. For the connection, the drivers FreeTDS (www.freetds.org) and UnixODBC
(www.unixodbc.org) are used.

4.2.1.1 Configure MS SQL-Server for Remote Access


With a freshly installed Microsoft SQL Server, remote access is disabled by default. With the Microsoft SQL
Server Management Studio, remote access can be enabled.

Rigth-clicking on the server and selecting properties opens the settings window.

31/208
Under connections, the checkbox allow remote connections to this server can be selected.

Also, TCP/IP option must be activated under the settings in the SQL Server Configuration Manager:

4.2.1.2 Testing the Connection to the Port of the MS SQL Server


Testing whether the port of the MS SQL Server is available first can be done with the Linux computer. As in
Windows, this is done with telnet.
telnet <IP-Address> <Port number>
Example: telnet 192.168.25.1 1433

4.2.1.3 Installing Tools


If a connection to this port cannot be established, the corresponding port must be opened in the firewall
settings.

The tools FreeTDS and UnixODBC must be installed.

sudo apt-get install freetds-dev tdsodbc unixodbc unixodbc-dev , or simply execute the script PluginODBC-
inst in the Plugins folder of the file Setup_S4A_Linux.zip.

The settings of the connection must be adjusted in two files. These two files are odbc.ini and odbcinst.ini. In
our example, the two files are located in the path /etc.
The files can be opened with the pico text editor.
Example: sudo pico odbc.ini

32/208
4.2.1.4 odbcinst.ini
In the odbcinst.ini, the path of the ODBC driver is specified.
[<Treiberbezeichnung>]
Description = <TreiberDescription>
Driver = <Pfad des Treibers>
Beispiel:
[FreeTDS]
Description = FreeTDS
Driver = /usr/lib/i386-linux-gnu/odbc/libtdsodbc.so

4.2.1.5 odbc.ini
Die odbc.ini describes the connection to the MS SQL Server
[<Verbindungsbezeichnung>]
description = <VerbindungsDescription>
Driver = <Treiberbezeichnung aus odbcinst.ini>
Server = <IP-Adresse des MS SQL Servers>
Port = <Post des MS SQL Servers>
Database = <Datenbankbezeichnung>
Beispiel:
[SQL4automation]
description = "Verbindung zu MS SQL Server SQL4automation"
Driver = FreeTDS
Server = 192.168.25.1
Port = 1433
Database = SQL4A

4.2.1.6 Testing the ODBC Connection


To test whether the tools have been installed correctly and the ODBC connection has been configured
correctly, the command isql is executed.
isql -v <Verbindungsbezeichnung> <Benutzername MS SQL Server Benutzer> <Passwort MS SQL Server>
Beispiel: isql -v SQL4automation root sql4automation
It should be possible to successfully establish the connection:
+---------------------------------------+
| Connected! |
| |
| sql-statement |
| help [tablename] |
| quit |
| |
+---------------------------------------+
SQL>

4.2.1.7 Selecting the ODBC Connection in the SQL4automation Connector


In the link settings of the SQL4automation Connector, the ODBC connections entered into the odbc.ini can be
selected. As may be the case, the display must be reloaded first by clicking the “Update” button.

33/208
4.2.2 Direct Database Connection under Linux
Under Linux, the SQL4automation Connector provides direct database connection for the databases MySQL,
SQLite, IBM DB2, Borland InterBase, Oracle OCI and Sybase Adaptive Server TDS. However, the database
drivers must be installed first with the package management software of Linux. The respective script can be
executed in the folder Plugins of Setup_S4A_Linux.zip.

4.2.2.1 Creating a new direct Database Connection under Linux

Under Linux, DB Admin can be selected in the link settings.

By clicking “Add”, a new database connection can be created, clicking “Rename” allows changing its name.
The following entries are necessary:
Server: IP of the database server, if the server is located on the same PC as the Connector: 127.0.0.1,
For SQLite databases, the path to the database must be entered.
Database: Name of the database, with SQLite databases, here the name of the databse is entered.
User: User name
Password: Password

34/208
4.2.2.2 Selecting the Database Connection in the SQL4automation Connector
In the link settings of the SQL4automation Connectors, the database connections created in DB Admin can be
selected. As the case may be, the display must be reloaded first by clicking the “Update” button.

35/208
5 Target-Libraries
5.1 CODESYS V2.3 / SQL4CODESYS – Target: „Standard“

5.1.1 Requirements

The SQL4CoDeSys.lib library uses the sockets-function of the CoDeSys library SysLibSockets.lib, which must be
also added in the project in the library manager.
The sample project can be executed on the CODESYS Soft-PLC “PLCWinNT”, or on a Hardware PLC. However,
it is required that the control system has a TCP/IP connection, and that it supports the SysLibSockets.lib.

5.1.2 Function Block

5.1.3 Global Constants

Some global constants can be adjusted for project-specific purposes. Depending on the size of the data to be
read or written, the array sizes are configured here. These global parameters are declared in your project
(GVL_SQL4CoDeSys). Upon applying changes here, the complete project must be retranslated.

36/208
VAR_GLOBAL CONSTANT
diMaxRows : DINT := 50; (* max. Number Datasets, from Table-Array *)
diMaxColumns : DINT := 15; (* max. Number Columns, from Table-Array *)
diStringLength : DINT := 40; (* String-Length in the Table-Array*)
diUBoundRequestArray : DINT := 20; (* UpperBoundary Request-String-Array *)
diRequestStringLength : DINT := 80; (* String-Length Request-String-Array *)
diReadDataBuffer : DINT := 4096; (* max. Number Bytes of Read-Buffer *)
diSendDataBuffer : DINT := 2048; (* max. Number Bytes of Send-Buffer *)
END_VAR

5.1.4 Global Variables

VAR_GLOBAL
saRequest : ARRAY[1..diUBoundRequestArray] OF STRING(diRequestStringLength); (* Request-Array *)
saColumnsName : ARRAY[1..diMaxColumns] OF STRING(diStringLength); (* ColumnsName-Array *)
saTableValues : ARRAY[1..diMaxRows, 1..diMaxColumns] OF STRING(diStringLength); (* Values-Array *)
END_VAR

37/208
5.1.5 Instance / Interface
Creating the instance of the SQL4CoDeSys-Target-Library and creating local variables.

DB_Connection : SQL4CoDeSys; (* Instance of SQL4CoDeSys Function Block

xExecute : BOOL; (* Start Database request *)


xAbort : BOOL; (* Reset *)
sIPAddress : STRING(15) ; (* Set IP-Address of the SQL4automation-Connector *)
iPort : UINT; (* Set Port-Number of the SQL4automation-Connector *)
xHoldConnection : BOOL; (* Holds Socket connection open after Database request *)
timTimeOut : TIME; (* Timeout *)
xReady : BOOL; (* Ready for Database request *)
xBusy : BOOL; (* Database request in process *)
xDone : BOOL; (* Database request completed *)
xError : BOOL; (* Database request resulted in an Error *)
diResultState : DINT; (* Status Database request / Error number *)
diResultRows : DINT; (* Num. returned Rows from the Database request *)
diResultColumns : DINT; (* Num. returned Columns from the Database request *)

Opening the instance in the program and assigning local variables.

sIPAddress := '192.168.1.20'; (* IP address which is set in the Connector *)


iPort := 11001;
DB_Connection( xExecute:= xExecute,
xAbort:= xAbort,
sIPAddress:= sIPAddress,
iPort:= iPort,
xHoldConnection:= xHoldConnection,
tTimeOut:= timTimeOut,
pRequest:= ADR(saRequest),
pColumnName:= ADR(saColumnsName),
pTableValue:= ADR(saTableValues),
xReady=> xReady,
xBusy=> xBusy,
xDone=> xDone,
xError=> xError,
diResultState=> diResultState,
diResultRows=> diResultRows,
diResultColumns=> diResultColumns);

38/208
5.1.6 Handshake
The handshake is conducted in accordance with the handshake of the StandardProtocol. The
StandardProtocol is described under 6.1 Standard Protocol.

5.1.7 Error Codes Return-Value

The variable “diResultState” describes the error.


Error Number Error Description

1 Unknown SQL Command


2 Request returns more datasets than defined by diMaxRows, modify request or increase diMaxRows
3 Request returns more columns than defined by diMaxColumns, modify request or increase diMaxColumns
5 Request returns minimal one value that is bigger than defined by MaxStringLength, modify request or increase
MaxStringLength
10 Internal Connector error
11 Internal Connector error, cannot open database
21 No IP-address defined/ sIPAddress=’’
22 No port number defined / uiPort=0
23 Request string is empty/ pRequest ^[1]=’’
24 Number MaxRows not defined / diMaxRows=0
25 Number MaxColumns not defined / diMaxColumns=0
26 Pointer to TableValues-Array is not defined
27 Pointer to ColumnsName-Array is not defined
28 Pointer to Request-Array is not defined
29 Size MaxStringLength not defined / diStringLength=0
41 No connection to SQL4automation-Connector established.
Turn off Firewall.
50 Sending the complete request string has failed. Please check your connection or the TCP buffer of your system.
51 Request string is greater than the send buffer. (diSendDataBuffer)
71 Connection to the SQL4automation-Connector cannot be closed
99 Timeout
>100 Error numbers of the ODBC database connection (some known error numbers are attached)
40002 General error during SQL request, request string is invalid

39/208
5.1.8 Sample Project SQL4CoDeSysSample
In the sample project SQL4CoDeSysSample.pro, the SQL4CodeSys library has already been integrated.
The project can be tested on the CODESYS Soft-PLC “PLCWinNT”, for example. The connector must be
started, and the connection to the sample library “S4A_Test_DB.mdb” must be configured.
How to configure the connection to the test database is described under 4.1.1 Setting up the connection to
the test database.

By forcing xExecute, the program can be tested. In the case of an error, the connection can be reset by
forcing xAbort.
By forcing the variable xStartRequest, an automated execution of a database request can be performed.

40/208
As soon as the request has been successfully completed, the received data records are located in the global
variables.

41/208
5.2 CODESYS V3 / SQL4CODESYSV3 – Target: „Standard“

5.2.1 Requirements
This target requires CODESYS 3.5 as a minimum.
The function block SQL4CoDeSysV3 uses the sockets function of the CoDeSys library SysSocket. It is
integrated automatically when the library “SQL4CoDeSys V3” is added.
The sample project can be executed on the Soft-PLC “CODESYS Control Win V3”, or on a hardware-PLC.
However, it is required that the control system has a TCP/IP connection, and that it supports the library
SysSocket.

5.2.2 Installing the library


The library”SQL4CoDeSysV3.compiled-library” is installed via the library repository.

5.2.3 Function Block

5.2.4 Global Constants


Some global constants can be adjusted for project-specific purposes.
Depending on the size of the data to be read or written, the array sizes are configured here. These global
parameters are declared in the library under “GlobalParameters”. The values can be edited there.
(press space bar)

42/208
VAR_GLOBAL CONSTANT
gc_diMaxRows : DINT := 200; // max. Number Datasets (Table-Array)
gc_diMaxColumns : DINT := 15; // max. Number Columns (Table-Array)
gc_diStringLength : DINT := 40; // String-Length in the Table-Array
gc_diUBoundRequestArray : DINT := 20; // Arraysize Request-Array
gc_diRequestStringLength : DINT := 80; // String-Length Request-Array
gc_diReadDataBuffer : DINT := DINT#8192; // max. Number Bytes of Read-Buffer
gc_diSendDataBuffer : DINT := DINT#8192; // max. Number Bytes of Write-Buffer
gc_xSetOptionsAllowed : BOOL := TRUE; // Activates / deactivates Socket Setting Options, must be
deactivated with some control systems.
END_VAR

5.2.5 Global Variables


The global variables for the data are declared in the library under “GlobalVariables”.
VAR_GLOBAL
g_saRequest : ARRAY[1..diUBoundRequestArray] OF STRING(diRequestStringLength); // Request-Array
g_saColumnName : ARRAY[1..diMaxColumns] OF STRING(diStringLength); // ColumnsName-Array
g_saTableValue : ARRAY[1..diMaxRows, 1..diMaxColumns] OF STRING(diStringLength); // Values-Array
END_VAR

5.2.6 Instance / Interface


Creating the instance of the SQL4CoDeSysV3 function block and creating local variables.
VAR
DB_Connection : SQL4CoDeSysV3; // Instance of SQL4CoDeSysV3 Function Block

xExecute : BOOL; // Start Database request


xAbort : BOOL; // Reset
sIPAddress : STRING(15); // Set IP-Address of the SQL4automation-Connector
uiPort : UINT; // Set Port-Number of the SQL4automation-Connector
xHoldConnection : BOOL; // Holds Socket connection open after Database request
tTimeOut : TIME; // Timeout
xReady : BOOL; // Ready for Database request
xBusy : BOOL; // Database request in process
xDone : BOOL; // Database request completed
xError : BOOL; // Database request resulted in an Error
diResultState : DINT; // Status Database request / Error number
diResultRows : DINT; // Num. returned Rows from the Database request
diResultColumns : DINT; // Num. returned Columns from the Database request
END_VAR

43/208
Opening the instance in the program and assigning local variables.
sIPAddress := '192.168.1.20'; // IP address which is set in the Connector
iPort := 11001;
uiPort := 11001;
DB_Connection( xExecute:= xExecute,
xAbort:= xAbort,
sIPAddress:= sIPAddress,
uiPort:= uiPort,
xHoldConnection:= xHoldConnection,
tTimeOut:= T#30S,
pRequest:= ADR(g_saRequest),
pColumnName:= ADR(g_saColumnName),
pTableValue:= ADR(g_saTableValue),
xReady=> xReady,
xBusy=> xBusy,
xDone=> xDone,
xError=> xError,
diResultState=> diResultState,
diResultRows=> diResultRows,
diResultColumns=> diResultColumns,
Socket=> );

5.2.7 Handshake
The handshake is conducted in accordance with the handshake of the StandardProtocol. The
StandardProtocol is described under 6.1 Standard Protocol.

5.2.8 Error Codes Return-Value


The variable “diResultState” describes the error.
Error Number Error Description

1 Unknown SQL Command


2 Request returns more datasets than defined by diMaxRows, modify request or increase diMaxRows
3 Request returns more columns than defined by diMaxColumns, modify request or increase diMaxColumns
5 Request returns minimal one value that is bigger than defined by MaxStringLength, modify request or increase
MaxStringLength
10 Internal Connector error
11 Internal Connector error, cannot open database
21 No IP-address defined/ sIPAddress=’’
22 No port number defined / uiPort=0
23 Request string is empty/ pRequest^[1]=’’
24 Number MaxRows not defined / diMaxRows=0
25 Number MaxColumns not defined / diMaxColumns=0
26 Pointer to TableValues-Array is not defined
27 Pointer to ColumnsName-Array is not defined
28 Pointer to Request-Array is not defined
29 Size MaxStringLength not defined / diStringLength=0
41 No connection to SQL4automation-Connector established.
Turn off Firewall.
50 Sending the complete request string has failed. Please check your connection or the TCP buffer of your system.
51 Request string is greater than the send buffer. (diSendDataBuffer)
71 Connection to the SQL4automation-Connector cannot be closed
99 Timeout
>100 Error numbers of the ODBC database connection (some known error numbers are attached)
40002 General error during SQL request, request string is invalid

44/208
5.2.9 Sample Project SQL4CoDeSysV3_Sample.project
A project archive was created as a sample project. It is located in the folder “SQL4CODESYSV3\Sample” and
its name is SQL4CoDeSysV3_Sample.projectarchive.
However, it is also possible to add the library “SQL4CoDeSysV3_3.5.x.x.compiled-library” into an existing
project only.
It is even easier to install the SQL4CODESYS Package via the CODESYS-Store. This will automatically install the
SQL4CoDeSysV3 library.

45/208
The project can be tested on the CODESYS Soft-PLC “CODESYS Control Win V3”, for example. The connector
must be started, and the connection to the sample database “S4A_Test_DB.mdb” must be configured.

By forcing xExecute, the program can be tested. In the case of an error, the connection can be reset by
forcing xAbort. By forcing the variable xStartRequest, an automated execution of a database request can be
performed.

46/208
5.3 Beckhoff TwinCAT V2 / SQL4TwinCAT – Target: „Standard“

5.3.1 Requirements

The SQL4TwinCat.lib library uses the sockets functions of the Beckhoff library TcpIp.lib, which must also be
connected in the project in the library administration.
The sample project can be executed on the Soft-PLC “TwinCAT PLC”, or a hardware-PLC. However, it is
required that the control system has a TCP/IP connection, and that it supports the TcpIp.lib. To allow for the
Tcplp.lib to function, install the TwinCAT TCP/IP Server (CE) from Beckhoff on the control system. This
TwinCAT TCP/IP server is subject to licensing, or it runs in a 30 days demo mode.

5.3.2 Function Block

5.3.3 Global Constants

Some global constants can be adjusted for project-specific purposes. Depending on the size of the data to be
read or written, the array sizes are configured here. These global parameters are declared in your project
(GVL_SQL4TwinCAT). Upon applying changes here, the complete project must be retranslated.

47/208
VAR_GLOBAL CONSTANT
diMaxRows : DINT := 50; (* max. Number Datasets, from Table-Array *)
diMaxColumns : DINT := 15; (* max. Number Columns, from Table-Array *)
diStringLength : DINT := 40; (* String-Length in the Table-Array*)
diUBoundRequestArray : DINT := 20; (* UpperBoundary Request-String-Array *)
diRequestStringLength : DINT := 80; (* String-Length Request-String-Array *)
diReadDataBuffer : DINT := 4096; (* max. Number Bytes of Read-Buffer *)
diSendDataBuffer : DINT := 2048; (* max. Number Bytes of Send-Buffer *)
END_VAR

5.3.4 Global Variables

VAR_GLOBAL
saRequest : ARRAY[1..diUBoundRequestArray] OF STRING(diRequestStringLength); (* Request-Array *)
saColumnsName : ARRAY[1..diMaxColumns] OF STRING(diStringLength); (* ColumnsName-Array *)
saTableValues : ARRAY[1..diMaxRows, 1..diMaxColumns] OF STRING(diStringLength); (* Values-Array *)
END_VAR

48/208
5.3.5 Instance / Interface

Creating the instance of the SQL4TwinCAT-Target-Library and creating local variables.

DB_Connection : SQL4TwinCAT; (* Instance of SQL4CoDeSys Function Block

xExecute : BOOL; (* Start Database request *)


xAbort : BOOL; (* Reset *)
sIPAddress : STRING(15) ; (* Set IP-Address of the SQL4automation-Connector *)
iPort : UINT; (* Set Port-Number of the SQL4automation-Connector *)
xHoldConnection : BOOL; (* Holds Socket connection open after Database request *)
timTimeOut : TIME; (* Timeout *)
xReady : BOOL; (* Ready for Database request *)
xBusy : BOOL; (* Database request in process *)
xDone : BOOL; (* Database request completed *)
xError : BOOL; (* Database request resulted in an Error *)
diResultState : DINT; (* Status Database request / Error number *)
diResultRows : DINT; (* Num. returned Rows from the Database request *)
diResultColumns : DINT; (* Num. returned Columns from the Database request *)

Opening the instance in the program and assigning local variables.

sIPAddress := '192.168.1.20'; (* IP address which is set in the Connector *)


iPort := 11001;
DB_Connection( xExecute:= xExecute,
xAbort:= xAbort,
sIPAddress:= sIPAddress,
iPort:= iPort,
xHoldConnection:= xHoldConnection,
tTimeOut:= timTimeOut,
pRequest:= ADR(saRequest),
pColumnName:= ADR(saColumnsName),
pTableValue:= ADR(saTableValues),
xReady=> xReady,
xBusy=> xBusy,
xDone=> xDone,
xError=> xError,
diResultState=> diResultState,
diResultRows=> diResultRows,
diResultColumns=> diResultColumns);

49/208
5.3.6 Handshake
The handshake is conducted in accordance with the handshake of the StandardProtocol. The
StandardProtocol is described under 6.1 Standard Protocol.

5.3.7 Error Codes Return-Value

The variable “diResultState” describes the error.


Error Number Error Description
1 Unknown SQL Command
2 Request returns more datasets than defined by MaxRows, modify request or increase MaxRows
3 Request returns more columns than defined by MaxColumns, , modify request or increase MaxColumns
5 Request returns minimal one value that is bigger than defined by MaxStringLength, modify request or increase
MaxStringLength
10 Internal Connector error
11 Internal Connector error, cannot open database
21 No IP-address defined
22 No port number defined
23 Request string is empty
24 Number MaxRows not defined
25 Number MaxColumns not defined
26 Pointer to TableValues-Array is not defined
27 Pointer to ColumnsName-Array is not defined
28 Pointer to Request-Array is not defined
29 Size MaxStringLength not defined / diStringLength=0
41 No connection to SQL4automation-Connector established.
Turn off Firewall.
51 Error during sending of request
61 No data available for receipt
71 Connection to the SQL4automation-Connector cannot be closed
99 Timeout
>100 Error numbers of the ODBC database connection (some known error numbers are attached)
40002 General error during SQL request, request string is invalid

50/208
5.3.8 Sample Project SQL4TwinCATSample

In the sample project SQL4TwinCATSample, the SQL4TwinCAT library has already been integrated.
The project can be tested on the Soft-PLC „TwinCAT PLC“, for example. The connector must be started, and
the connection to the sample database “S4A_Test_DB.mdb” must be configured.
How to configure the connection to the test database is described under 4.1.1 Setting up the connection to
the test database.

By forcing xExecute, the program can be tested. In the case of an error, the connection can be reset by
forcing xAbort.
By forcing the variable xStartRequest, an automated execution of a database request can be performed.

51/208
As soon as the request has been successfully completed, the received data records are located in the global
variables.

52/208
5.4 Beckhoff TwinCAT V3 / SQL4TwinCAT3 – Target: „Standard“

5.4.1 Requirements
The SQL4TwinCAT3 function block requires the following libraries: Tc2_TcpIp.lib, Tc2_Standard, Tc2_System.
These libraries must be added in the project under references.
The Tc2_TcpIp.lib is part of the TCP/IP server license, which must be ordered from Beckhoff (order-nr. TF6310
- TC3 TCP/IP). For testing purposes, a 7-days testing license can be activated under System License. This
activation can be performed several times.

The sample project can be executed on the Soft-PLC of TwinCAT3, or on a hardware-PLC.


However, it is required that the control system has a TCP/IP connection, and that it supports the
Tc2_TcpIp.lib.
Also for the Soft-PLC of TwinCAT3 (order-nr. TC1200- TC3 PLC), a 7-days testing license can be activated. This
activation can be performed several times.

5.4.2 Function Block

5.4.3 Global Constants


Some global constants can be adjusted for project-specific purposes. Depending on the size of the data to be
read or written, the array sizes are configured here. These global parameters are declared in your project
(GVL_SQL4TwinCAT3). Upon applying changes here, the complete project must be retranslated.

53/208
VAR_GLOBAL CONSTANT
gc_diMaxRows : DINT := 200; // max. Number Datasets (Table-Array)
gc_diMaxColumns : DINT := 15; // max. Number Columns (Table-Array)
gc_diStringLength : DINT := 40; // String-Length in the Table-Array
gc_diUBoundRequestArray : DINT := 20; // Arraysize Request-Array
gc_diRequestStringLength : DINT := 80; // String-Length Request-Array
gc_diReadDataBuffer : DINT := DINT#8192; // max. Number Bytes of Read-Buffer
gc_diSendDataBuffer : DINT := DINT#8192; // max. Number Bytes of Write-Buffer
gc_xSetOptionsAllowed : BOOL := TRUE; // Activates / deactivates Socket Setting Options, must be
deactivated with some control systems.
END_VAR

5.4.4 Global Variables


The global variables for the data are declared in your project (GVL_SQL4TwinCAT3).

VAR_GLOBAL
g_saRequest : ARRAY[1..diUBoundRequestArray] OF STRING(diRequestStringLength); // Request-Array
g_saColumnName : ARRAY[1..diMaxColumns] OF STRING(diStringLength); // ColumnsName-Array
g_saTableValue : ARRAY[1..diMaxRows, 1..diMaxColumns] OF STRING(diStringLength); // Values-Array
END_VAR

5.4.5 Instance / Interface


Creating the instance of the SQL4TwinCAT3 function block and creating locale variables:

VAR
DB_Connection : SQL4TwinCAT3; // Instance of SQL4TwinCAT3 Function Block

xExecute : BOOL; // Start Database request


xAbort : BOOL; // Reset
sIPAddress : STRING(15); // Set IP-Address of the SQL4automation-Connector
uiPort : UINT; // Set Port-Number of the SQL4automation-Connector
xHoldConnection : BOOL; // Holds Socket connection open after Database request
tTimeOut : TIME; // Timeout
xReady : BOOL; // Ready for Database request
xBusy : BOOL; // Database request in process
xDone : BOOL; // Database request completed
xError : BOOL; // Database request resulted in an Error
diResultState : DINT; // Status Database request / Error number
diResultRows : DINT; // Num. returned Rows from the Database request
diResultColumns : DINT; // Num. returned Columns from the Database request
END_VAR

54/208
Opening the instance in the program and assigning local variables.

sIPAddress := '192.168.1.20'; // also 'localhost' possible


uiPort := 11001;
DB_Connection( xExecute:= xExecute,
xAbort:= xAbort,
sIPAddress:= sIPAddress,
uiPort:= uiPort,
xHoldConnection:= xHoldConnection,
tTimeOut:= T#30S,
pRequest:= ADR(g_saRequest),
pColumnName:= ADR(g_saColumnName),
pTableValue:= ADR(g_saTableValue),
xReady=> xReady,
xBusy=> xBusy,
xDone=> xDone,
xError=> xError,
diResultState=> diResultState,
diResultRows=> diResultRows,
diResultColumns=> diResultColumns,
Socket=> );

5.4.6 Handshake
The handshake is conducted in accordance with the handshake of the StandardProtocol. The
StandardProtocol is described under 6.1 Standard Protocol.

5.4.7 Error Codes Return-Value


The variable “diResultState” describes the error.
Error Number Error Description

1 Unknown SQL Command


2 Request returns more datasets than defined by gc_diMaxRows, modify request or increase gc_diMaxRows
3 Request returns more columns than defined by gc_diMaxColumns, modify request or increase gc_diMaxColumns
5 Request returns minimal one value that is bigger than defined by MaxStringLength, modify request or increase
MaxStringLength
10 Internal Connector error
11 Internal Connector error, cannot open database
21 No IP-address defined/ sIPAddress=’’
22 No port number defined / uiPort=0
23 Request string is empty/ pRequest^[1]=’’
24 Number MaxRows not defined / gc_diMaxRows=0
25 Number MaxColumns not defined / gc_diMaxColumns=0
26 Pointer to TableValue-Array is not defined
27 Pointer to ColumnName-Array is not defined
28 Pointer to Request-Array is not defined
29 Send buffer too small (gc_diSendDataBuffer<=gc_diRequestStringLength)
30 Send buffer too small ( gc_diSendDataBuffer<5)
51 Request string is greater than the send buffer. (gc_diSendDataBuffer)
71 Connection to the SQL4automation-Connector cannot be closed
99 Timeout
>100 Error numbers of the ODBC database connection (some known error numbers are attached)
40002 General error during SQL request, request string is invalid

55/208
5.4.8 Sample Project SQL4TwinCAT3 Sample program
As a sample project, a Microsoft Visual Studio Solution was created. It is located in the folder “SQL4TwinCAT3
Sample program”. There is also a PLC project archive and a Solution project archive in this folder.
However, it is also possible to add the function block “SQL4TwinCAT3” and the global list of variables
“GVL_SQL4TwinCAT3” into an existing project.

The project can be tested on the TC3 Soft-PLC. The connector must be started, and the connection to the
sample database “S4A_Test_DB.mdb” must be configured.
How to configure the connection to the test database is described under 4.1.1 Setting up the connection to
the test database.

56/208
By forcing xExecute, the program can be tested. In the case of an error, the connection can be reset by
forcing xAbort.
By forcing the variable xStartRequest, an automated execution of a database request can be performed.

57/208
5.5 Stäubli VAL3 / SQL4Val3 – Target: „Staeubli Val3“

5.5.1 Requirements
The SQL4Val3 Target-Library can be used on Stäubli CS8C control systems from Val3 Version 7.0 and up.
The sample project can be executed in the emulator contained in Stäubli Robotics Studio, or on a Stäubli
CS8C control system.

5.5.2 Instance / Interface

Input-Data
sioSocket: sioSocket Socket for the Connection.
SQL4ARequest
sRequest: String Array SQL Request
Output-Data
SQL4AResult
nRows: num Number of rows of result of SQL request
nColumns: num Number of columns of result of SQL Request
nState: num Status of request
sHeaders String Array Column names of result
sValues 2 dimensional String Array Return values of result

58/208
5.5.3 Creating the Socket

Creating a new socket under system control.

The socket is defined as client, and as SQL4automation by default.

The following settings can be modified:


Server address: IP address of the Connector computer. For testing with the Emulator of the SRS, here the
internal IP address 127.0.0.1 is used, as the Emulator and Connector are located on the same PC.
Port: The port can be selected freely. By default from 11001 and up.
Time Out: Time in seconds until an exception is triggered.
End of String Default 13

59/208
5.5.4 Integrating the Library and user-defined Data Types into Val3 Project
In the sample project, the libraries and user-defined data types have already been entered into the project.
These steps are not necessary for executing the sample project. However, for the creation of an own project,
the integration of a library and user-defined data types into a project is described in the following.

Projects
SQL4Val3 Actual program for the SQL queries.
main The sample program which demonstrates the integration of SQL4Val3.

Data Types
S4ARequest Data type for the SQL request
S4AResult Data type for the SQL result

Integrating Data Types and Libraries

User-defined data types and libraries are integrated into the project in Stäubli Robotics Studio under the
References tab.
By right-clicking on the project to which a reference is to be added, “new library” for adding a new library and
“new user-defined data type” for adding a new data type can be selected.
WIth S4ARequest.sRequest[0]=”SELECT …” the variables of the structure can be accessed
Performing the call
call SQL4Val3:SQL4Val3(sioSocket,S4ARequest,S4AResult)
executes an SQL request.

60/208
5.5.5 Sample Project SQL4Val3Sample
Testing the Project
The ethernet connection between Controller/Emulator and SQL4automation Connector and database must
be established. The connector must be started, and the connection to the sample database
“S4A_Test_DB.mdb” must be configured.
How to configure the connection to the test database is described under 4.1.1 Setting up the connection to
the test database.

Start the main application on the Emulator or the CS8C-Controller.

5.5.6 Error Codes Return-Value


Error Number Error Description

1 Unknown SQL Command


2 Request returns more datasets than number of columns S4AResult.sValues, modify request or increase number of
columns S4AResult.sValues
3 Request returns more columns than number of columns S4AResult.sValues, , modify request or increase number
of columns S4AResult.sValues
5 Request returns minimal one value that is bigger than defined by MaxStringLength, modify request or increase
MaxStringLength
10 Internal Connector error
11 Internal Connector error, cannot open database
23 Request string is empty
24 Number MaxRows not defined
25 Number MaxColumns not defined
29 Size MaxStringLength not defined / diStringLength=0
>100 Error numbers of the ODBC database connection (some known error numbers are attached)

61/208
5.6 S7-1200 / S7-1500 TIA13 StringTable / SQL4Siemens – Target: “Siemens S7”
There are two examples for Siemens S7-1200 respectively S7-1500. On the one hand the version StringTable,
on the other the version DataBuffer.
The example “StringTable” uses string arrays for sending respectively receiving the data. The advantage is
that the data that is being sent and received may be controlled easily. The drawback: the example requires
more storage space on the CPU (23087 bytes). This example is recommended to users, who use
SQL4automation in connection with Siemens S7 for the first time.

5.6.1 Requirements

The communication works on all Siemens S7-1200 and Siemens S7-1500 control systems via the Profinet
interface.

The following blocks are required for the connection to the Connector:
• dbSQLUserData
• idbSQL4Siemens
• All blocks in the folder SQL4Siemens under program blocks
• TRCV_C (S7-1200) / TRCV (S7-1500)
• TSEND_C
• All data types in the SQL4Siemens folder under PLC data type

62/208
5.6.1.1 Calling of fbSQL4Siemens
The fbSQL4Siemens is called cyclically, e.g. in the Main [OB1]. The following parameters are set:

5.6.1.2 Parameters of fbSQL4Siemens


xExecute : BOOL; // Start database query

iIP1 : INT; // 1. digit of the configured IP address of the SQL4automation-


Connectors
iIP2 : INT; // 2. digit of the configured IP address of the SQL4automation-
Connectors
iIP3 : INT; // 3. digit of the configured IP address of the SQL4automation-
Connectors
iIP4 : INT; // 4. digit of the configured IP address of the SQL4automation-
Connectors

iRemotePort : INT; // Configured port number of the SQL4automation-Connectors


iLocalPort : INT; // Port that is used locally on the control
tTimeout : TIME // Timeout in seconds
stUserRequest : utSQL4SiemensUserRequest // Request structure
stUserResponse : utSQL4SiemensUserResponse // Response structure
xAbort : BOOL; // Reset
xHoldConnection : BOOL; // Keeps the socket connection open after a database query

iConnectionID : INT; // Distinct ID of the connection


wLocalDeviceID : BYTE; // Controller type
- B#16#01: S7-1200, S7-1500

xReady : BOOL; // Ready for a database query


xBusy : BOOL; // Database query is running
xDone : BOOL; // Database query completed
xError : BOOL; // Database query ended with an error

diResultState : DINT; // Status database query / error number


diResultRows : DINT; // Number of received rows from the database query
diResultColumns : DINT; // Number of received columns from the database query

63/208
5.6.2 Data modules
iDBSQL4Siemens – instance data module for the internal usage of the function block SQL4Siemens.
dbSQLUserData – user data such as request string array or response string table

5.6.3 Data types (UDT)

utSQL4SiemensUserRequest – contains the request string array and the corresponding size.

utSQL4SiemensUserResponse – contains the response string table and the information about number of
columns, number of records and string length.

utDataBuffer – data buffer for sending and receiving the SQL query, contains the buffer-byte-array and the
corresponding size.

5.6.4 Auxiliary functions

The SQL4Siemens library provides a number of auxiliary functions. These functions are used to convert from a
data type to string or string to another data type. In case no auxiliary functions are provided, this case may be
solved with the standard Siemens functions. The auxiliary functions are located under program block,
SQL4Siemens, convert functions.

STRING := fcByte2String(Input: BYTE bValue);

64/208
STRING := fcDint2FormattedString(Input: DINT diValue, INT iLen);
iLen indicates the number of characters that the string needs to have. diValue := 25, iLen := 4 ergibt '0025'.

STRING := fcDint2String(Input: DINT diValue);

STRING := fcDt2String(Input: DTL dtlTimestamp, STRING sTemplate);


Converts a DTL variable to a string. In doing so the format of sTemplate is used. sTemplate may include the
following placeholders:

Label Description Default Value Number of Characters


@Y@ year 1970 4
@M@ month 1 2
@D@ day 1 2
@h@ hour 0 2
@m@ minute 0 2
@s@ second 0 2
@ms@ millisecond 0 3

For example: sTemplate := '@Y@/@m@/@D@ @h@:@m@:@s@:@ms@' submits the return value


'2014/09/15 20:15:21:15'

STRING := fcDWord2String(Input: DWORD dwValue);

STRING := fcInt2String(Input: INT iValue);

STRING := fcLreal2String(Input: LREAL lrValue, INT iFractionalDigits);


iFractionalDigits indicates the number of fractional digits

STRING := fcReal2String(Input: REAL rValue, INT iFractionalDigits);


iFractionalDigits indicates the number of fractional digits

DTL := fcString2DT(STRING sTimestamp, STRING sTemplate);


Converts a string to a DTL. sTemplate equally composes as sTemplate for the function fcDt2String.

STRING := fcUdint2String(Input: UDINT udiValue);

STRING := fcUint2String(Input: UDINT uiValue);

STRING := fcWord2String(Input: WORD wValue);

65/208
5.6.5 Data area
Some data types may be adapted to the specific project. Depending on the size of the data volume to be read
or written, the array or data type values are determined here.

utSQL4SiemensUserRequest
The size of the request-string-array and the string length may be changed.
cdiRequestArraySize has to correspond to the size of the asRequest arrays.

utSQL4SiemensUserResponse
The number of columns and the number of records of the receive-string-array and the string length may be
changed. The data marked in colors have to correlate.

66/208
utDataBuffer
The value of the sending and receiving data buffer can be set.

5.6.6 Configuration of the Connector

For the selected Siemens-target in the Connector further options have to be defined:

 Receive buffer Size of the receive buffer in the utDataBuffer


 CP 343-1 Interface Deactivate
 Fix Buffer Deactivate

67/208
5.6.7 Ethernet interface settings
In order to establish a communication via the Ethernet interface on the CPU and the Connector, it has to be
parameterized. The IP address of the Ethernet interface has to be in the same network address range as the
one of the Connector.

The different network cards are arranged under “online access”. Select the network card, which is connected
to the control and scan the network via “update accessible devices”. The control appears. A new IP address
and subnet mask can be assigned under “functions”, “assign IP address” and sent to the control via the
button “assign IP address”.

68/208
5.6.8 The sample project
The sample project of the website is executable and, prior to adaptations to the own application, should be
made running first. Thus possible sources of error may be located more easily.

Only the IP address and the remote port have to be adapted to your system when calling up the SQL4Siemens
in the OB1.

The Connector has to be started and the connection to the sample database “S4A_Test_DB.mdb” has to be
configured.
How to configure the connection to the test database is described under 4.1.1 Setting up the connection to
the test database.
The sample program shows how to write into the database, how to read from the database and how to
delete values in the database. In addition, it demonstrates how variables are converted to string and written
into the SQL request string and how values from the response string table are converted and saved in
variables.

An example how a SQL request is written in the request string array:

"dbSQLUserData".stRequest.asRequest[0] := 'SELECT id, iParam1, fParam2, sText1 FROM tTable1';

An example how a value of the response string table is copied to a variable:

"iParamFromDB" := STRING_TO_INT("dbSQLUserData".stResponse.asData[0,1]);

In doing so, the value of the cell [0,1] is written into the Integer iParamFromDB.

In this sample program, the requests are copied in string arrays and values of string tables are read. This
option is more user-friendly, but more memory-intensive.

69/208
5.6.8.1 Loading of the sample program
The program may be loaded to the CPU via the button “download to device”. The connection path has to be
selected for the first connection. In doing so, “PN/IE” is selected for “type of the PG/PC interface”, and the
network card connected to the control for the “PG/PC interface” and “PN/IE_1” for the connection
interface/subnet”.
The control may be searched via “start search”. The control is selected and the project is loaded to the
control via the button load.

In case the project on the PC differs too much from the project on the control, which is the case when loading
for the first time, the control has to be stopped.

After the loading, the control is restarted.

70/208
5.6.8.2 Handling of the sample program
A watch and force table has been created. It is located under watch and force tables, SQL4automation.

Via xReset the current request is cancelled, ilnsertValue is reset to 0 and Main[OB1].
Afterwards the process in the Main [OB1] starts again.

xHoldConnection keeps the connection to the Connector open. Thus requests in quick succession are faster,
because the connection to the Connector does not have to be set up for each request and to be closed again
after the request.

71/208
5.6.9 Error codes Return-Value
The variable “diResultState” describes the error.
Error number Error description
1 Unknown SQL command
2 Query returns more data records than defined with MaxRows, adjust query or increase MaxRows
3 Query returns more columns than defined with MaxColumns, adjust query or increase MaxColumns
4 Query returns more data than the defined buffer size.
adjust query or enlarge buffer size in the Connector and in the control
5 Query returns at least one value, which is bigger than defined with MaxStringLength,
adjust query or enlarge MaxStringLength
10 Internal Connector error
11 Internal Connector error, database cannot be opened
21 No IP address defined
22 No port number defined
23 Request-String is empty
24 Number MaxRows not defined
25 Number MaxColumns not defined
29 Value MaxStringLength not defined
41 No connection to the SQL4automation-Connector established. Turn off the firewall. Check IP and remote port.
51 Error in sending the query. Turn off the firewall. Check IP and remote port.
61 Error in receiving the data
71 Connection to the SQL4automation-Connector cannot be closed
>100 Error number of the ODBC database connection
40002 General error during the SQL query, Request-String is invalid

72/208
5.7 S7-1200 / S7-1500 TIA13 DataBuffer / SQL4Siemens – Target: „Siemens S7“
There are two examples for Siemens S7-1200 respectively S7-1500. On the one hand the version StringTable,
on the other the version DataBuffer.
The example “DataBuffer” requires only one buffer byte array. The query string is directly copied to the
buffer, the data directly converted from the buffer to the variables. The advantage of this: Less storage space
is required (20000 bytes), however the example is less user-friendly, because the data may not be simply
displayed in a string table.

5.7.1 Requirements

The communication works on all Siemens S7-1200 and Siemens S7-1500 control systems via the Profinet
interface.

The following blocks are required for the connection to the Connector:
• dbSQLUserData
• idbSQL4Siemens
• All blocks in the folder SQL4Siemens under program blocks
• TRCV_C (S7-1200) / TRCV (S7-1500)
• TSEND_C
• All data types in the SQL4Siemens folder under PLC data type

73/208
5.7.1.1 Calling of fbSQL4Siemens
The fbSQL4Siemens is called cyclically, e.g. in the Main [OB1]. The following parameters are set:

5.7.1.2 Parameters of fbSQL4Siemens


xExecute : BOOL; // Start database query

iIP1 : INT; // 1. digit of the configured IP address of the SQL4automation-


Connectors
iIP2 : INT; // 2. digit of the configured IP address of the SQL4automation-
Connectors iIP3 : INT; // 3. digit of the configured IP address of the
SQL4automation-Connectors iIP4 : INT; // 4. digit of the configured IP address of the
SQL4automation-Connectors

iRemotePort : INT; // Configured port number of the SQL4automation-Connectors


iLocalPort : INT; // Port that is used locally on the control
tTimeout : TIME // Timeout in seconds
stRequestBuffer : utDataBuffer // Data buffer for the request
stResponseBuffer : utDataBuffer // Data buffer for the response
stUserResponse : utSQL4SiemensUserResponse // Response structure
xAbort : BOOL; // Reset
xHoldConnection : BOOL; // Keeps the socket connection open after a database query

iConnectionID : INT; // Distinct ID of the connection


wLocalDeviceID : BYTE; // Controller type
- B#16#01: S7-1200, S7-1500

xReady : BOOL; // Ready for a database query


xBusy : BOOL; // Database query is running
xDone : BOOL; // Database query completed
xError : BOOL; // Database query ended with an error

diResultState : DINT; // Status database query / error number


diResultRows : DINT; // Number of received rows from the database query
diResultColumns : DINT; // Number of received columns from the database query

74/208
5.7.2 Data modules
iDBSQL4Siemens – instance data module for the internal usage of the function block SQL4Siemens.
dbSQLUserData – user data such as request string array or response string table

5.7.3 Data types (UDT)


utSQL4SiemensStringInfo – this structure is used in utSQL4SiemensUserResponse. It serves the localization of
the data in the buffer.

utSQL4SiemensUserResponse – contains the information of the response and of the number of columns,
number of records and string length.
adiColName is an array that indicates where the column names are located in the buffer.
adiData is an array that indicates where the individual data is located in the buffer.

utDataBuffer – data buffer for sending and receiving the SQL query, contains the buffer-byte-array and the
corresponding size.

5.7.4 Auxiliary functions


The SQL4Siemens library provides a number of auxiliary functions. These functions are used to convert from a
data type to string or string to another data type. In case no auxiliary functions are provided, this case may be
solved with the standard Siemens functions. The auxiliary functions are located under program block,
SQL4Siemens, convert functions.

75/208
STRING := fcByte2String(Input: BYTE bValue);

STRING := fcDint2FormattedString(Input: DINT diValue, INT iLen);


iLen indicates the number of characters that the string needs to have. diValue := 25, iLen := 4 ergibt '0025'.

STRING := fcDint2String(Input: DINT diValue);

STRING := fcDt2String(Input: DTL dtlTimestamp, STRING sTemplate);


Converts a DTL variable to a string. In doing so the format of sTemplate is used. sTemplate may include the
following placeholders:

Label Description Default Value Number of Characters


@Y@ year 1970 4
@M@ month 1 2
@D@ day 1 2
@h@ hour 0 2
@m@ minute 0 2
@s@ second 0 2
@ms@ millisecond 0 3

For example: sTemplate := '@Y@/@m@/@D@ @h@:@m@:@s@:@ms@' submits the return value


'2014/09/15 20:15:21:15'

STRING := fcDWord2String(Input: DWORD dwValue);

STRING := fcInt2String(Input: INT iValue);

STRING := fcLreal2String(Input: LREAL lrValue, INT iFractionalDigits);


iFractionalDigits indicates the number of fractional digits

STRING := fcReal2String(Input: REAL rValue, INT iFractionalDigits);


iFractionalDigits indicates the number of fractional digits

DTL := fcString2DT(STRING sTimestamp, STRING sTemplate);


Converts a string to a DTL. sTemplate equally composes as sTemplate for the function fcDt2String.

STRING := fcUdint2String(Input: UDINT udiValue);

STRING := fcUint2String(Input: UDINT uiValue);

STRING := fcWord2String(Input: WORD wValue);

76/208
5.7.5 Data area
Some data types may be adapted to the specific project. Depending on the size of the data volume to be read
or written, the array or data type values are determined here.

utSQL4SiemensUserResponse
The number of columns and the number of records of the receice-string-array and the string length may be
changed. The data marked in colors have to correlate.

77/208
utDataBuffer
The value of the sending and receiving data buffer may be set.

5.7.6 Configuration of the Connector

For the selected Siemens-target in the Connector further options have to be defined:

 Receive buffer Size of the receive buffer in the utDataBuffer


 CP 343-1 Interface Deactivate
 Fix Buffer Deactivate

78/208
5.7.7 Ethernet interface settings
In order to establish a communication via the Ethernet interface on the CPU and the Connector, it has to be
parameterized. The IP address of the Ethernet interface has to be in the same network address range as the
one of the Connector.

The different network cards are arranged under “online access”. Select the network card, which is connected
to the control and scan the network via “update accessible devices”. The control appears. A new IP address
and subnet mask can be assigned under “functions”, “assign IP address” and sent to the control via the
button “assign IP address”.

79/208
5.7.8 The sample project
The sample project of the website is executable and, prior to adaptations to the own application, should be
made running first. Thus possible sources of error may be located more easily.

Only the IP address and the remote port have to be adapted to your system when calling up the SQL4Siemens
in the OB1.

The Connector has to be started and the connection to the sample database “S4A_Test_DB.mdb” has to be
configured.
How to configure the connection to the test database is described under 4.1.1 Setting up the connection to
the test database.
The sample program shows how to write into the database, how to read from the database and how to
delete values in the database. In addition, it is demonstrated how variables are written into the SQL request
data buffer and how values from the response data buffer are saved in variables.

An example how a SQL request is written into the data buffer:

"xRet" := "fcSQL4Siemens_BufferAddRequestString"(pDataBuffer := "dbSQLUserData".stRequestBuffer,


sValue := 'SELECT id, iParam1, fParam2, sText1 FROM tTable1 WHERE id = (SELECT MAX(id) FROM tTable1)',
pResponseData := "dbSQLUserData".stResponse);

An example how a value from the buffer is copied in a variable:

"iParamFromDB" := STRING_TO_INT("fcSQL4Siemens_BufferReadString2"(pDataBuffer :=
"dbSQLUserData".stResponseBuffer, stStringInfo := "dbSQLUserData".stResponse.adiData[0, 1]));

In doing so, the value of the cell [0,1] is written into the Integer iParamFromDB.

Since the additional string array and the string table are omitted in this example, the example requires less
storage, but is also less user-friendly.

80/208
5.7.8.1 Loading of the sample program
The program may be loaded to the CPU via the button “download to device”. The connection path has to be
selected for the first connection. In doing so, “PN/IE” is selected for “type of the PG/PC interface”, and the
network card connected to the control for the “PG/PC interface” and “PN/IE_1” for the connection
interface/subnet”.
The control may be searched via “start search”. The control is selected and the project is loaded to the
control via the button load.

In case the project on the PC differs too much from the project on the control, which is the case when loading
for the first time, the control has to be stopped.

After the loading, the control is restarted.

81/208
5.7.8.2 Handling of the sample program
A watch and force table has been created. It is located under watch and force tables, SQL4automation.

Via xReset the current request is cancelled, ilnsertValue is reset to 0 and Main[OB1].
Afterwards the process in the Main [OB1] starts again.

xHoldConnection keeps the connection to the Connector open. Thus requests in quick succession are faster,
because the connection to the Connector does not have to be set up for each request and to be closed again
after the request.

82/208
5.7.9 Error codes Return-Value
The variable “diResultState” describes the error.
Error number Error description
1 Unknown SQL command
2 Query returns more records than defined with MaxRows, adjust query or increase MaxRows
3 Query returns more columns than defined with MaxColumns, adjust query or increase MaxColumns
4 Query returns more data than the defined buffer size.
adjust query or enlarge buffer size in the Connector and in the control
5 Query returns at least one value, which is bigger than defined with MaxStringLength,
adjust query or enlarge MaxStringLength
10 Internal Connector error
11 Internal Connector error, database cannot be opened
21 No IP address defined
22 No port number defined
23 Request-String is empty
24 Number MaxRows not defined
25 Number MaxColumns not defined
29 Value MaxStringLength not defined
41 No connection to the SQL4automation-Connector established. Turn off the firewall. Check IP and remote port.
51 Error in sending the query. Turn off the firewall. Check IP and remote port.
61 Error in receiving the data
71 Connection to the SQL4automation-Connector cannot be closed
>100 Error number of the ODBC database connection
40002 General error during the SQL query, Request-String is invalid

83/208
5.8 S7-300 PN/DP, IM151-8, WinAC RTX TIA13 / SQL4Siemens – Target: „Siemens S7“
There are three examples for S7-300, IM151-8 and WinAC RTX controls. One in TIA13, one in SIMATIC
Manager V5.5 ST and one in SIMATIC Manager V5.5 Ladder/IL.

5.8.1 Requirements

The communication works on all S7-300 PN/DP, IM151-8 and WinAC RTX control systems with Profinet-
interface.

The following blocks are required for the connection to the Connector:
• dbSQLUserData
• idbSQL4Siemens
• All blocks in the folder SQL4Siemens under program blocks
• All system blocks
• All data types in the folder SQL4Siemens under PLC data type

84/208
5.8.1.1 Calling of fbSQL4Siemens
The fbSQL4Siemens is called cyclically, e.g. in the obMain [OB1]. The following parameters are set:

5.8.1.2 Parameters of fbSQL4Siemens


xExecute : BOOL; // Start database query

iIP1 : INT; // 1. digit of the configured IP address of the SQL4automation-


Connectors
iIP2 : INT; // 2. digit of the configured IP address of the SQL4automation-
Connectors
iIP3 : INT; // 3. digit of the configured IP address of the SQL4automation-
Connectors
iIP4 : INT; // 4. digit of the configured IP address of the SQL4automation-
Connectors

iRemotePort : INT; // Configured port number of the SQL4automation-Connectors


iLocalPort : INT; // Port that is used locally on the control
tTimeout : TIME // Timeout in seconds
xAbort : BOOL; // Reset
xHoldConnection : BOOL; // Keeps the socket connection open after a database query

iConnectionID : INT; // Distinct ID of the connection


wLocalDeviceID : BYTE; // Controller type
- B#16#01: IM151-8
- B#16#02: CPU 31x-2 PN/DP,
CPU 314C-2 PN/DP,
IM154-8 CPU.
- B#16#03: CPU 319-3 PN/DP
- B#16#05: CPU 412-2 PN,
CPU 414-3 PN/DP,
CPU 416-3 PN/DP,
CPU 41x-5H PN/DP (Rack 0)
- B#16#05: CPU 41x-5H PN/DP (Rack 1)
- B#16#01: WinAC RTX Ethernet interface at interface slot 1 (IF1)
- B#16#06: WinAC RTX Ethernet interface at interface slot 2 (IF2)
- B#16#0B: WinAC RTX Ethernet interface at interface slot 3 (IF3)
- B#16#0F: WinAC RTX Ethernet interface at interface slot 4 (IF4)

85/208
wConnectionType : BYTE; // Connection type
- B#16#01: TCP/IP native (compatibility mode)
- B#16#11: TCP/IP native (firmware 2.4 and up)

stUserRequest : utSQL4SiemensUserRequest // Request structure


stUserResponse : utSQL4SiemensUserResponse // Response structure

xReady : BOOL; // Ready for a database query


xBusy : BOOL; // Database query is running
xDone : BOOL; // Database query completed
xError : BOOL; // Database query ended with an error

diResultState : DINT; // Status database query / error number


diResultRows : DINT; // Number of received rows from the database query
diResultColumns : DINT; // Number of received columns from the database query

5.8.2 Data modules


iDBSQL4Siemens – instance data module for the internal usage of the function block SQL4Siemens.
dbSQLUserData – user data such as request string array or response string table

5.8.3 Data types (UDT)

utSQL4SiemensUserRequest – contains the request string array and the corresponding size.

utSQL4SiemensUserResponse – contains the response string table and the information about number of
columns, number of records and string length.

utDataBuffer – data buffer for sending and receiving the SQL query, contains the buffer-byte-array and the
corresponding size.

86/208
5.8.4 Auxiliary functions
The SQL4Siemens library provides a number of auxiliary functions. These functions are used to convert from a
data type to string or string to another data type. In case no auxiliary functions are provided, this case may be
solved with the standard Siemens functions. The auxiliary functions are located under program block,
SQL4Siemens, convert functions.

STRING := fcByte2String(Input: BYTE bValue);

STRING := fcDint2FormattedString(Input: DINT diValue, INT iLen);


iLen indicates the number of characters that the string needs to have. diValue := 25, iLen := 4 ergibt '0025'.

STRING := fcDint2String(Input: DINT diValue);

STRING := fcDt2String(Input: DTL dtlTimestamp, STRING sTemplate);


Converts a DTL variable to a string. In doing so the format of sTemplate is used. sTemplate may include the
following placeholders:

Label Description Default Value Number of Characters


@Y@ year 1970 4
@M@ month 1 2
@D@ day 1 2
@h@ hour 0 2
@m@ minute 0 2
@s@ second 0 2
@ms@ millisecond 0 3

For example: sTemplate := '@Y@/@m@/@D@ @h@:@m@:@s@:@ms@' submits the return value


'2014/09/15 20:15:21:15'

STRING := fcInt2String(Input: INT iValue);

STRING := fcReal2String(Input: REAL rValue, INT iFractionalDigits);


iFractionalDigits indicates the number of fractional digits

DTL := fcString2DT(STRING sTimestamp, STRING sTemplate);

87/208
Converts a string to a DTL. sTemplate equally composes as sTemplate for the function fcDt2String.

STRING := fcWord2String(Input: WORD wValue);

5.8.5 Data area


Some data types may be adapted to the specific project. Depending on the size of the data volume to be read
or written, the array or data type values are determined here.

utSQL4SiemensUserRequest
The size of the request-string-array and the string length may be changed.
cdiRequestArraySize has to correspond to the size of the asRequest arrays.

utSQL4SiemensUserResponse
The number of columns and the number of records of the receive-string-array and the string length may be
changed. The data marked in colors have to correlate.

88/208
utDataBuffer
The value of the sending and receiving data buffer can be set.

5.8.6 Configuration of the Connector

For the selected Siemens-target in the Connector further options have to be defined:

 Receive buffer Size of the receive buffer in the utDataBuffer


 CP 343-1 Interface Deactivate
 Fix Buffer Deactivate

89/208
5.8.7 Ethernet interface settings
In order to establish a communication via the Ethernet interface on the CPU and the Connector, it has to be
parameterized. The IP address of the Ethernet interface has to be in the same network address range as the
one of the Connector.

The different network cards are arranged under “online access”. Select the network card, which is connected
to the control and scan the network via “update accessible devices”. The control appears. A new IP address
and subnet mask can be assigned under “functions”, “assign IP address” and sent to the control via the
button “assign IP address”.

90/208
5.8.8 The sample project
The sample project of the website is executable and, prior to adaptations to the own application, should be
made running first. Thus possible sources of error may be located more easily.

Only the IP address and the remote port have to be adapted to your system when calling up the SQL4Siemens
in the OB1.

The Connector has to be started and the connection to the sample database “S4A_Test_DB.mdb” has to be
configured.
How to configure the connection to the test database is described under 4.1.1 Setting up the connection to
the test database.
The sample program shows how to write into the database, how to read from the database and how to
delete values in the database. In addition, it demonstrates how variables are converted to string and written
into the SQL request string and how values from the response string table are converted and saved in
variables.

An example how a SQL request is written in the request string array:

"dbSQLUserData".stRequest.asRequest[0] := 'SELECT id, iParam1, fParam2, sText1 FROM tTable1';

An example how a value of the response string table is copied to a variable:

"iParamFromDB" := STRING_TO_INT("dbSQLUserData".stResponse.asData[0,1]);

In doing so, the value of the cell [0,1] is written into the Integer iParamFromDB.

In this sample program, the requests are copied in string arrays and values of string tables are read. This
option is more user-friendly, but more memory-intensive.

91/208
5.8.8.1 Loading of the sample program
The program may be loaded to the CPU via the button “download to device”. The connection path has to be
selected for the first connection. In doing so, “PN/IE” is selected for “type of the PG/PC interface”, and the
network card connected to the control for the “PG/PC interface” and “PN/IE_1” for the connection
interface/subnet”.
The control may be searched via “start search”. The control is selected and the project is loaded to the
control via the button load.

In case the project on the PC differs too much from the project on the control, which is the case when loading
for the first time, the control has to be stopped.

92/208
After the loading, the control is restarted.

5.8.8.2 Handling of the sample program


A watch and force table has been created. It is located under watch and force tables, SQL4automation.

Via xReset the current request is cancelled, ilnsertValue is reset to 0 and Main[OB1].
Afterwards the process in the Main [OB1] starts again.

xHoldConnection keeps the connection to the Connector open. Thus requests in quick succession are faster,
because the connection to the Connector does not have to be set up for each request and to be closed again
after the request.

93/208
5.8.9 Error codes Return-Value
The variable “diResultState” describes the error.
Error number Error description
1 Unknown SQL command
2 Query returns more data records than defined with MaxRows, adjust query or increase MaxRows
3 Query returns more columns than defined with MaxColumns, adjust query or increase MaxColumns
4 Query returns more data than the defined buffer size.
adjust query or enlarge buffer size in the Connector and in the control
5 Query returns at least one value, which is bigger than defined with MaxStringLength,
adjust query or enlarge MaxStringLength
10 Internal Connector error
11 Internal Connector error, database cannot be opened
21 No IP address defined
22 No port number defined
23 Request-String is empty
24 Number MaxRows not defined
25 Number MaxColumns not defined
29 Value MaxStringLength not defined
41 No connection to the SQL4automation-Connector established. Turn off the firewall. Check IP and remote port.
51 Error in sending the query. Turn off the firewall. Check IP and remote port.
61 Error in receiving the data
71 Connection to the SQL4automation-Connector cannot be closed
>100 Error number of the ODBC database connection
40002 General error during the SQL query, Request-String is invalid

94/208
5.9 S7-300 CP-343 TIA13 / SQL4Siemens – Target: „Siemens S7“
There are three examples for S7-300, IM151-8 and WinAC RTX controls. One in TIA13, one in SIMATIC
Manager V5.5 ST and one in SIMATIC Manager V5.5 Ladder/IL.

5.9.1 Requirements
The following blocks are required for the connection to the Connector:
• dbSQLUserData
• idbSQL4Siemens
• All blocks in the folder SQL4Siemens under program blocks
• All system blocks
• All data types in the folder SQL4Siemens under PLC data type

95/208
5.9.1.1 Calling of fbSQL4Siemens
The fbSQL4Siemens is called cyclically, e.g. in the obMain [OB1]. The following parameters are set:

5.9.1.2 Parameter von fbSQL4Siemens


xExecute : BOOL; // Start database query

tTimeout : TIME // Timeout in seconds


xAbort : BOOL; // Reset
iID : INT; // Distinct ID of the connection

stRequestBuffer : utDataBuffer // Data buffer for the request


stResponseBuffer : utDataBuffer // Data buffer for the response

xReady : BOOL; // Ready for a database query


xBusy : BOOL; // Database query is running
xDone : BOOL; // Database query completed
xError : BOOL; // Database query ended with an error

diResultState : DINT; // Status database query / error number


diResultRows : DINT; // Number of received rows from the database query
diResultColumns : DINT; // Number of received columns from the database query

5.9.2 Data modules

iDBSQL4Siemens – instance data module for the internal usage of the function block SQL4Siemens.
dbSQLUserData – user data such as request string array or response string table

5.9.3 Data types (UDT)

utSQL4SiemensUserRequest – contains the request string array and the corresponding size.

96/208
utSQL4SiemensUserResponse – contains the response string table and the information about number of
columns, number of records and string length.

utDataBuffer – data buffer for sending and receiving the SQL query, contains the buffer-byte-array and the
corresponding size.

97/208
5.9.4 Setting of the IP address of the CPs
Unter „devices & networks“, Doppelklick auf die gewünschte SPS und Anklicken des CPs können die
Einstellungen des CPs verändert werden. Unter „Ethernet addresses“ kann die IP des CPs eingestellt werden.

5.9.5 Adding a new network connection

If the communication has been resolved via a communication processor, the connection parameters cannot
be set directly in the program code as in the PN/DP version, but a new network connection has to be created.

A network connection can be added under “devices & networks”, Connections by a right click on the CPU,
“Add new connection”.

98/208
In the following window the TCP connection, the CP and “establish active connection” have to be selected.

The connection can be selected under the tab Connections. Under Properties, Address details, the IP and the
port of the connector link are being set.

99/208
When calling the SQL4Siemens program block the ID of the connection has to be entered.

5.9.6 Auxiliary functions

The SQL4Siemens library provides a number of auxiliary functions. These functions are used to convert from a
data type to string or string to another data type. In case no auxiliary functions are provided, this case may be
solved with the standard Siemens functions. The auxiliary functions are located under program block,
SQL4Siemens, convert functions.

STRING := fcByte2String(Input: BYTE bValue);

100/208
STRING := fcDint2FormattedString(Input: DINT diValue, INT iLen);
iLen indicates the number of characters that the string needs to have. diValue := 25, iLen := 4 ergibt '0025'.

STRING := fcDint2String(Input: DINT diValue);

STRING := fcDt2String(Input: DTL dtlTimestamp, STRING sTemplate);


Converts a DTL variable to a string. In doing so the format of sTemplate is used. sTemplate may include the
following placeholders:

Label Description Default Value Number of Characters


@Y@ year 1970 4
@M@ month 1 2
@D@ day 1 2
@h@ hour 0 2
@m@ minute 0 2
@s@ second 0 2
@ms@ millisecond 0 3

For example: sTemplate := '@Y@/@m@/@D@ @h@:@m@:@s@:@ms@' submits the return value


'2014/09/15 20:15:21:15'

STRING := fcInt2String(Input: INT iValue);

STRING := fcReal2String(Input: REAL rValue, INT iFractionalDigits);


iFractionalDigits indicates the number of fractional digits

DTL := fcString2DT(STRING sTimestamp, STRING sTemplate);


Converts a string to a DTL. sTemplate equally composes as sTemplate for the function fcDt2String.

STRING := fcWord2String(Input: WORD wValue);

101/208
5.9.7 Data area
Some data types may be adapted to the specific project. Depending on the size of the data volume to be read
or written, the array or data type values are determined here.

utSQL4SiemensUserRequest
The size of the request-string-array and the string length may be changed.
cdiRequestArraySize has to correspond to the size of the asRequest arrays.

utSQL4SiemensUserResponse
The number of columns and the number of records of the receive-string-array and the string length may be
changed. The data marked in colors have to correlate.

102/208
utDataBuffer
The value of the sending and receiving data buffer can be set.

5.9.8 Configuration of the Connector

For the selected Siemens-target in the Connector further options have to be defined:

 Receive buffer Size of the receive buffer in the utDataBuffer


 CP 343-1 Interface Activate
 Fix Buffer Activate

103/208
5.9.9 Ethernet interface settings
To load the program from the PC to the control, an IP has to be assigned to the control.

The different network cards are arranged under “online access”. Select the network card, which is connected
to the control and scan the network via “update accessible devices”. The control appears. A new IP address
and subnet mask can be assigned under “functions”, “assign IP address” and sent to the control via the
button “assign IP address”.

104/208
5.9.10 The sample project
The sample project of the website is executable and, prior to adaptations to the own application, should be
made running first. Thus possible sources of error may be located more easily.

The network connection has to be adapted to the project as described under 5.9.5 .Adding a new network
connection.

The Connector has to be started and the connection to the sample database “S4A_Test_DB.mdb” has to be
configured.

How the connection to the test database is established is described under 4.1.1 Setting up the connection to
the test database.

The sample program shows how to write into the database, how to read from the database and how to
delete values in the database. In addition, it demonstrates how variables are converted to string and written
into the SQL request string and how values from the response string table are converted and saved in
variables.

An example how a SQL request is written in the request string array:

"dbSQLUserData".stRequest.asRequest[0] := 'SELECT id, iParam1, fParam2, sText1 FROM tTable1';

An example how a value of the response string table is copied to a variable:

"iParamFromDB" := STRING_TO_INT("dbSQLUserData".stResponse.asData[0,1]);

In doing so, the value of the cell [0,1] is written into the Integer iParamFromDB.

105/208
5.9.10.1 Loading of the sample program
The program may be loaded to the CPU via the button “download to device”. The connection path has to be
selected for the first connection. In doing so, “PN/IE” is selected for “type of the PG/PC interface”, and the
network card connected to the control for the “PG/PC interface” and “PN/IE_1” for the connection
interface/subnet”.
The control may be searched via “start search”. The control is selected and the project is loaded to the
control via the button load.

In case the project on the PC differs too much from the project on the control, which is the case when loading
for the first time, the control has to be stopped.

106/208
After the loading, the control is restarted.

5.9.10.2 Handling of the sample program


A watch and force table has been created. It is located under watch and force tables, SQL4automation.

Via xReset the current request is cancelled, ilnsertValue is reset to 0 and Main[OB1].
Afterwards the process in the Main [OB1] starts again.

107/208
5.9.11 Error codes Return-Value
The variable “diResultState” describes the error.
Error number Error description
1 Unknown SQL command
2 Query returns more data records than defined with MaxRows, adjust query or increase MaxRows
3 Query returns more columns than defined with MaxColumns, adjust query or increase MaxColumns
4 Query returns more data than the defined buffer size.
adjust query or enlarge buffer size in the Connector and in the control
5 Query returns at least one value, which is bigger than defined with MaxStringLength,
adjust query or enlarge MaxStringLength
10 Internal Connector error
11 Internal Connector error, database cannot be opened
21 No IP address defined
22 No port number defined
23 Request-String is empty
24 Number MaxRows not defined
25 Number MaxColumns not defined
29 Value MaxStringLength not defined
41 No connection to the SQL4automation-Connector established. Turn off the firewall. Check IP and remote port.
51 Error in sending the query. Turn off the firewall. Check IP and remote port.
61 Error in receiving the data
71 Connection to the SQL4automation-Connector cannot be closed
>100 Error number of the ODBC database connection
40002 General error during the SQL query, Request-String is invalid

108/208
5.10 S7-300 PN/DP, IM151-8, WinAC RTX SIMATIC Manager ST / SQL4Siemens – Target:
„Siemens S7“
There are three examples for S7-300, IM151-8 and WinAC RTX controls. One in TIA13, one in SIMATIC
Manager V5.5 ST and one in SIMATIC Manager V5.5 Ladder/IL.

5.10.1 Requirements
The following blocks are required for the connection to the Connector:
• All blocks and source in the folder S7-programm

109/208
5.10.1.1 Calling of fbSQL4Siemens
The fbSQL4Siemens is called cyclically, e.g. in the Main [OB1]. The following parameters are set:

5.10.1.2 Parameters of fbSQL4Siemens


xExecute : BOOL; // Start database query

iIP1 : INT; // 1. digit of the configured IP address of the SQL4automation-


Connectors
iIP2 : INT; // 2. digit of the configured IP address of the SQL4automation-
Connectors
iIP3 : INT; // 3. digit of the configured IP address of the SQL4automation-
Connectors
iIP4 : INT; // 4. digit of the configured IP address of the SQL4automation-
Connectors

iRemotePort : INT; // Configured port number of the SQL4automation-Connectors


iLocalPort : INT; // Port that is used locally on the control
tTimeout : TIME // Timeout in seconds
xAbort : BOOL; // Reset
xHoldConnection : BOOL; // Keeps the socket connection open after a database query

iConnectionID : INT; // Distinct ID of the connection


wLocalDeviceID : BYTE; // Controller type
- B#16#01: IM151-8
- B#16#02: CPU 31x-2 PN/DP,
CPU 314C-2 PN/DP,
IM154-8 CPU.
- B#16#03: CPU 319-3 PN/DP
- B#16#05: CPU 412-2 PN,
CPU 414-3 PN/DP,
CPU 416-3 PN/DP,
CPU 41x-5H PN/DP (Rack 0)
- B#16#05: CPU 41x-5H PN/DP (Rack 1)
- B#16#01: WinAC RTX Ethernet interface at interface slot 1 (IF1)
- B#16#06: WinAC RTX Ethernet interface at interface slot 2 (IF2)
- B#16#0B: WinAC RTX Ethernet interface at interface slot 3 (IF3)
- B#16#0F: WinAC RTX Ethernet interface at interface slot 4 (IF4)

110/208
wConnectionType : BYTE; // Connection type
- B#16#01: TCP/IP native (compatibility mode)
- B#16#11: TCP/IP native (firmware 2.4 and up)

stUserRequest : utSQL4SiemensUserRequest // Request structure


stUserResponse : utSQL4SiemensUserResponse // Response structure

xReady : BOOL; // Ready for a database query


xBusy : BOOL; // Database query is running
xDone : BOOL; // Database query completed
xError : BOOL; // Database query ended with an error

diResultState : DINT; // Status database query / error number


diResultRows : DINT; // Number of received rows from the database query
diResultColumns : DINT; // Number of received columns from the database query

5.10.2 Data modules


iDBSQL4Siemens – instance data module for the internal usage of the function block SQL4Siemens.
dbSQLUserData – user data such as request string array or response string table

5.10.3 Data types (UDT)

utSQL4SiemensUserRequest – contains the request string array and the corresponding size.

utSQL4SiemensUserResponse – contains the response string table and the information about number of
columns, number of records and string length.

utDataBuffer – data buffer for sending and receiving the SQL query, contains the buffer-byte-array and the
corresponding size.

111/208
5.10.4 Auxiliary functions
The SQL4Siemens library provides a number of auxiliary functions. These functions are used to convert from a
data type to string or string to another data type. In case no auxiliary functions are provided, this case may be
solved with the standard Siemens functions. The auxiliary functions are located under program block,
SQL4Siemens, convert functions.

STRING := fcByte2String(Input: BYTE bValue);

STRING := fcDint2FormattedString(Input: DINT diValue, INT iLen);


iLen indicates the number of characters that the string needs to have. diValue := 25, iLen := 4 ergibt '0025'.

STRING := fcDint2String(Input: DINT diValue);

STRING := fcDt2String(Input: DTL dtlTimestamp, STRING sTemplate);


Converts a DTL variable to a string. In doing so the format of sTemplate is used. sTemplate may include the
following placeholders:

Label Description Default Value Number of Characters


@Y@ year 1970 4
@M@ month 1 2
@D@ day 1 2
@h@ hour 0 2
@m@ minute 0 2
@s@ second 0 2
@ms@ millisecond 0 3

For example: sTemplate := '@Y@/@m@/@D@ @h@:@m@:@s@:@ms@' submits the return value


'2014/09/15 20:15:21:15'

STRING := fcInt2String(Input: INT iValue);

STRING := fcReal2String(Input: REAL rValue, INT iFractionalDigits);


iFractionalDigits indicates the number of fractional digits

DTL := fcString2DT(STRING sTimestamp, STRING sTemplate);


Converts a string to a DTL. sTemplate equally composes as sTemplate for the function fcDt2String.

STRING := fcWord2String(Input: WORD wValue);

112/208
5.10.5 Data area
Some data types may be adapted to the specific project. Depending on the size of the data volume to be read
or written, the array or data type values are determined here. The data types have to be changed under
sources and not under blocks. After changing the data types you have to open and compile MakeAll.

utSQL4SiemensUserRequestST
The size of the request-string-array and the string length may be changed.
cdiRequestArraySize has to correspond to the size of the asRequest arrays.

utSQL4SiemensUserResponseST
The number of columns and the number of records of the receive-string-array and the string length may be
changed. The data marked in colors have to correlate.

113/208
utDataBuffer
The value of the sending and receiving data buffer can be set.

5.10.6 Configuration of the Connector

For the selected Siemens-target in the Connector further options have to be defined:

 Receive buffer Size of the receive buffer in the utDataBuffer


 CP 343-1 Interface Deactivate
 Fix Buffer Deactivate

114/208
5.10.7 Ethernet interface settings
In order to establish a communication via the Ethernet interface on the CPU and the Connector, it has to be
parameterized. The IP address of the Ethernet interface has to be in the same network address range as the
one of the Connector.

To load the program from the PC to the control, an IP has to be assigned to the control.

By double-clicking on the PN-IO, Properties the property window of the PN-IO interface of the CPU is opened.
Here the IP address and the subnet mask can be changed.

By clicking on the button “load to module”, the current hardware configuration can be loaded into the CPU.
Display/Update shows all accessible CPUs. Select desired CPU and download current hardware configuration.

115/208
5.10.8 Changing of the block address
In case there are already blocks with the same address in your project, the SQL4automation blocks are set to
a different address as follows:

Open the symbol table and change the respective address.

116/208
Adjust the object name of the blocks to be changed.

Open under Source MakeAll and compile.

117/208
5.10.9 The sample project
The sample project of the website is executable and, prior to adaptations to the own application, should be
made running first. Thus possible sources of error may be located more easily.

Only the IP address and the remote port have to be adapted to your system when calling up the SQL4Siemens
in the OB1.

The Connector has to be started and the connection to the sample database “S4A_Test_DB.mdb” has to be
configured.
How to configure the connection to the test database is described under 4.1.1 Setting up the connection to
the test database.
The sample program shows how to write into the database, how to read from the database and how to
delete values in the database. In addition, it demonstrates how variables are converted to string and written
into the SQL request string and how values from the response string table are converted and saved in
variables.

An example how a SQL request is written in the request string array:

"dbSQLUserData".stRequest.asRequest[0] := 'SELECT id, iParam1, fParam2, sText1 FROM tTable1';

An example how a value of the response string table is copied to a variable:

"iParamFromDB" := STRING_TO_INT("dbSQLUserData".stResponse.asData[0,1]);

In doing so, the value of the cell [0,1] is written into the Integer iParamFromDB.

118/208
5.10.9.1 Loading of the sample program
The program can be loaded via the load button.

5.10.9.2 Handling of the sample program


The variables table VAT1 is located under blocks. In this variables table the individual variables can be
monitored and forced.

Via xReset the current request is cancelled, ilnsertValue is reset to 0 and Main[OB1].
Afterwards the process in the Main [OB1] starts again.

xHoldConnection keeps the connection to the Connector open. Thus requests in quick succession are faster,
because the connection to the Connector does not have to be set up for each request and to be closed again
after the request.

119/208
5.10.10 Error codes Return-Value
The variable “diResultState” describes the error.
Error number Error description
1 Unknown SQL command
2 Query returns more data records than defined with MaxRows, adjust query or increase MaxRows
3 Query returns more columns than defined with MaxColumns, adjust query or increase MaxColumns
4 Query returns more data than the defined buffer size.
adjust query or enlarge buffer size in the Connector and in the control
5 Query returns at least one value, which is bigger than defined with MaxStringLength,
adjust query or enlarge MaxStringLength
10 Internal Connector error
11 Internal Connector error, database cannot be opened
21 No IP address defined
22 No port number defined
23 Request-String is empty
24 Number MaxRows not defined
25 Number MaxColumns not defined
29 Value MaxStringLength not defined
41 No connection to the SQL4automation-Connector established. Turn off the firewall. Check IP and remote port.
51 Error in sending the query. Turn off the firewall. Check IP and remote port.
61 Error in receiving the data
71 Connection to the SQL4automation-Connector cannot be closed
>100 Error number of the ODBC database connection
40002 General error during the SQL query, Request-String is invalid

120/208
5.11 S7-300 CP-343 SIMATIC Manager ST / SQL4Siemens – Target: „Siemens S7“
There are three examples for S7-300, IM151-8 and WinAC RTX controls. One in TIA13, one in SIMATIC
Manager V5.5 ST and one in SIMATIC Manager V5.5 Ladder/IL.

5.11.1 Requirements
The following blocks are required for the connection to the Connector:
• All blocks and source in the folder S7-programm

121/208
5.11.1.1 Calling of fbSQL4Siemens
The fbSQL4Siemens is called cyclically, e.g. in the obMain [OB1]. The following parameters are set:

5.11.1.2 Parameter of fbSQL4Siemens


xExecute : BOOL; // Start database query

tTimeout : TIME // Timeout in seconds


xAbort : BOOL; // Reset
iID : INT; // Distinct ID of the connection

stRequestBuffer : utDataBuffer // Data buffer for the request


stResponseBuffer : utDataBuffer // Data buffer for the response

xReady : BOOL; // Ready for a database query


xBusy : BOOL; // Database query is running
xDone : BOOL; // Database query completed
xError : BOOL; // Database query ended with an error

diResultState : DINT; // Status database query / error number


diResultRows : DINT; // Number of received rows from the database query
diResultColumns : DINT; // Number of received columns from the database query

5.11.2 Data modules

iDBSQL4Siemens – instance data module for the internal usage of the function block SQL4Siemens.
dbSQLUserData – user data such as request string array or response string table

5.11.3 Data types (UDT)

utSQL4SiemensUserRequestST – contains the request string array and the corresponding size.

utSQL4SiemensUserResponseST – contains the response string table and the information about number of
columns, number of records and string length.

122/208
utDataBuffer – data buffer for sending and receiving the SQL query, contains the buffer-byte-array and the
corresponding size.

5.11.4 Setting of the IP address of the CPs

The setting of the IP address of the communication processor is done in the hardware configuration.

123/208
The settings of the CPs can be changed under “devices & networks”, by double-clicking on the desired SPS
and clicking on the CPs. The IP of the CPs can be changed under “Ethernet address”.

5.11.5 Adding of a new network connection

If the communication has been resolved via a communication processor, the connection parameters cannot
be set directly in the program code as in the PN/DP version, but a new network connection has to be created.

By double-clicking on Ethernet the NetPro configuration is opened.

A network connection can be added under “devices & networks”, Connections by a right click on the CPU,
“Add new connection”.

124/208
In the following window the TCP connection, the CP and “establish active connection” have to be selected.

The connection can be selected under the tab Connections. Under Properties, Address details, the IP and the
port of the connector link are being set.
With Saving and compiling the current settings are saved and checked for errors. When calling the
SQL4Siemens program module the ID of the connection has to be entered.

125/208
5.11.6 Hilfsfunktionen
The SQL4Siemens library provides a number of auxiliary functions. These functions are used to convert from a
data type to string or string to another data type. In case no auxiliary functions are provided, this case may be
solved with the standard Siemens functions. The auxiliary functions are located under program block,
SQL4Siemens, convert functions.

STRING := fcByte2String(Input: BYTE bValue);

STRING := fcDint2FormattedString(Input: DINT diValue, INT iLen);


iLen indicates the number of characters that the string needs to have. diValue := 25, iLen := 4 ergibt '0025'.

STRING := fcDint2String(Input: DINT diValue);

STRING := fcDt2String(Input: DTL dtlTimestamp, STRING sTemplate);


Converts a DTL variable to a string. In doing so the format of sTemplate is used. sTemplate may include the
following placeholders:

Label Description Default Value Number of Characters


@Y@ year 1970 4
@M@ month 1 2
@D@ day 1 2
@h@ hour 0 2
@m@ minute 0 2
@s@ second 0 2
@ms@ millisecond 0 3

For example: sTemplate := '@Y@/@m@/@D@ @h@:@m@:@s@:@ms@' submits the return value


'2014/09/15 20:15:21:15'

STRING := fcInt2String(Input: INT iValue);

STRING := fcReal2String(Input: REAL rValue, INT iFractionalDigits);


iFractionalDigits indicates the number of fractional digits

DTL := fcString2DT(STRING sTimestamp, STRING sTemplate);


Converts a string to a DTL. sTemplate equally composes as sTemplate for the function fcDt2String.

STRING := fcWord2String(Input: WORD wValue);

126/208
5.11.7 Data area
Some data types may be adapted to the specific project. Depending on the size of the data volume to be read
or written, the array or data type values are determined here. The data types have to be changed under
sources and not under blocks. After changing the data types you have to open and compile MakeAll.

utSQL4SiemensUserRequestST
The size of the request-string-array and the string length may be changed.
cdiRequestArraySize has to correspond to the size of the asRequest arrays.

utSQL4SiemensUserResponseST
The number of columns and the number of records of the receive-string-array and the string length may be
changed. The data marked in colors have to correlate.

127/208
utDataBuffer
The value of the sending and receiving data buffer can be set.

5.11.8 Configuration of the Connector

For the selected Siemens-target in the Connector further options have to be defined:

 Receive buffer Size of the receive buffer in the utDataBuffer


 CP 343-1 Interface Activate
 Fix Buffer Activate

128/208
5.11.9 Settings of the ethernet port
To load the program from the PC to the control, an IP has to be assigned to the control.

The IP address of the CPU can be changed in the hardware configuration and loaded to the control.

By double-clicking on the PN-IO, Properties the property window of the PN-IO interface of the CPU is opened.
Here the IP address and the subnet mask can be changed.

By clicking on the button “load to module”, the current hardware configuration can be loaded into the CPU.
Display/Update shows all accessible CPUs. Select desired CPU and download current hardware configuration.

129/208
5.11.10 Changing of the block addresses
In case there are already blocks with the same address in your project, the SQL4automation blocks are set to
a different address as follows:

Open the symbol table and change the respective address.

130/208
Adjust the object name of the blocks to be changed.

Open under Source MakeAll and compile.

131/208
5.11.11 The sample project
The sample project of the website is executable and, prior to adaptations to the own application, should be
made running first. Thus possible sources of error may be located more easily.

The network connection has to be adapted to the project as described under 5.9.5 Adding a new network
connection.

The Connector has to be started and the connection to the sample database “S4A_Test_DB.mdb” has to be
configured.
How to configure the connection to the test database is described under 4.1.1 Setting up the connection to
the test database.
The sample program shows how to write into the database, how to read from the database and how to
delete values in the database. In addition, it demonstrates how variables are converted to string and written
into the SQL request string and how values from the response string table are converted and saved in
variables.

An example how a SQL request is written in the request string array:

"dbSQLUserData".stRequest.asRequest[0] := 'SELECT id, iParam1, fParam2, sText1 FROM tTable1';

An example how a value of the response string table is copied to a variable:

"iParamFromDB" := STRING_TO_INT("dbSQLUserData".stResponse.asData[0,1]);

In doing so, the value of the cell [0,1] is written into the Integer iParamFromDB.

5.11.11.1 Loading oft he sample project


The program can be loaded via the load button.

132/208
5.11.11.2 Handling of the sample program
The variables table VAT1 is located under Modules. In this variables table the individual variables can be
monitored and forced.

Via xReset the current request is cancelled, ilnsertValue is reset to 0 and Main[OB1].
Afterwards the process in the Main [OB1] starts again.

133/208
5.11.12 Error codes Return-Value
The variable “diResultState” describes the error.
Error number Error description
1 Unknown SQL command
2 Query returns more data records than defined with MaxRows, adjust query or increase MaxRows
3 Query returns more columns than defined with MaxColumns, adjust query or increase MaxColumns
4 Query returns more data than the defined buffer size.
adjust query or enlarge buffer size in the Connector and in the control
5 Query returns at least one value, which is bigger than defined with MaxStringLength,
adjust query or enlarge MaxStringLength
10 Internal Connector error
11 Internal Connector error, database cannot be opened
21 No IP address defined
22 No port number defined
23 Request-String is empty
24 Number MaxRows not defined
25 Number MaxColumns not defined
29 Value MaxStringLength not defined
41 No connection to the SQL4automation-Connector established. Turn off the firewall. Check IP and remote port.
51 Error in sending the query. Turn off the firewall. Check IP and remote port.
61 Error in receiving the data
71 Connection to the SQL4automation-Connector cannot be closed
>100 Error number of the ODBC database connection
40002 General error during the SQL query, Request-String is invalid

134/208
5.12 S7-300 PN/DP, IM151-8, WinAC RTX SIMATIC Manager IL, Ladder/ SQL4Siemens –
Target: „Siemens S7“

5.12.1 Requirements
The communication functions on all S7-300 PN/DP and IM151-8 control systems (Ethernet interface on the
CPU).

The following blocks are required for the connection to the Connector:
• FB200 Function Block SQL4Siemens
• DB200 Instance Data Block SQL4Siemens
• DB201 Data Block S4A_saRequest (SQL Command Array)
• DB202 Data Block S4A_saColumnName (Column Name Array)
• DB203 Data Block S4A_saTableValue (Data Array)
• UDT1000 Structure S4A_saRequest (DB201)
• UDT1001 Structure S4A_saColumnName (DB202)
• UDT1002 Structure S4A_saTableValue (DB203)
• UDT1003 Structure S4A_saConstVarStruct (DB200)

• FB63 TSEND
• FB64 TRECV
• FB65 TCON
• FB66 TDISCON
• UDT65 TCON_PAR

135/208
5.12.2 Function Block (FB)

5.12.2.1 Call FB200


The FB200 is called on a cyclic basis, e.g. in OB1. The following parameters are defined:

 IP address of the Connector

 Port number of the Connector

 Control system type:


- B#16#01: IM151-8
- B#16#02: CPU 31x-2 PN/DP,
CPU 314C-2 PN/DP,
IM154-8 CPU.
- B#16#03: CPU 319-3 PN/DP
- B#16#05: CPU 412-2 PN,
CPU 414-3 PN/DP,
CPU 416-3 PN/DP,
CPU 41x-5H PN/DP (Rack 0)
- B#16#05: CPU 41x-5H PN/DP (Rack 1).

 Connection type:
- B#16#01: TCP/IP native (compatibility mode)
- B#16#11: TCP/IP native (firmware 2.4 and up)

Pointer anlegen für:


- saQuery (DB201)
- saColumnName (DB202)
- saTableValue (DB203)

136/208
5.12.2.2 Parameter of FB200

IP_1 : INT; // 1. Digit of set IP address of the SQL4automation-Connector


IP_2 : INT; // 2. Digit of set IP address of the SQL4automation-Connector
IP_3 : INT; // 3. Digit of set IP address of the SQL4automation-Connector
IP_4 : INT; // 4. Digit of set IP address of the SQL4automation-Connector

Port : INT; // Set Port-Number of the SQL4automation-Connector


Device : BYTE; // Control system type
- B#16#01: IM151-8
- B#16#02: CPU 31x-2 PN/DP, CPU 314C-2 PN/DP, IM154-8 CPU.
- B#16#03: CPU 319-3 PN/DP
ConnectionType : BYTE; // Control system type
- B#16#01: TCP/IP native (compatibility mode)
- B#16#11: TCP/IP native (firmware 2.4 and up)

xRestart : BOOL; // Restart CPU


xExecute : BOOL; // Start Database request
xAbort : BOOL; // Reset
xHoldConnection : BOOL; // Holds Socket connection open after Database request

timTimeOut : TIME; // Timeout in Seconds, Default 30s

ptRequest : ANY; // Pointer to saRequest (DB201)


ptColumnName : ANY; // Pointer to saColumnName (DB202)
ptTableValue : ANY; // Pointer to saTableValue (DB203)

xReady : BOOL; // Ready for Database request


xBusy : BOOL; // Database request in process
xDone : BOOL; // Database request completed
xError : BOOL; // Database request resulted in an Error

diResultState : DINT; // Status Database request / Error number


diResultRows : DINT; // Num. returned Rows from the Database request
diResultColumns : DINT; // Num. returned Columns from der Database request
wStatus : WORD; // Status of S7-Moduls TCON, TDISCON, TSEND, TRCV

5.12.3 Data Blocks (DB)


DB200 – Instance Data Block for internal use of Function Block SQL4Siemens (FB200).
DB201 – This Data Block contains the SQL Command to the SQL Database (Request).
DB202 – This Data Block contains the Column Names of the read-out Database Table (ColumnName).
DB203 – This Data Block contains the Data (Table Values) of the read-out Database Table (TableValue).
DB210 – This Data Block is only used in the Sample Program for easier entry of the SQL Command.
DB220 – This Data Block is only used in the Sample Program for read-out of the Database Values.

137/208
5.12.4 Data Types (UDT)
UDT1000 – Defines the Data Structure of DB201 (Size of SQL Command / Request)

UDT1001 – Defines the Data Structure of DB202 (Size of Columns Name / ColumnsName)

UDT1002 – Defines the Data Structure of DB203 (Size of Table Values / TableValues)

UDT1003 – Defines the Global Variables for Determining the Size of the various Tables.

138/208
5.12.5 Data Region
Some data types can be adjusted for project-specific purposes. Depending on the size of the data to be read
or written, the Array or Data Type sizes are configured here.

 FB200
The size of the Send and Receive Buffer:
- S_baSendBuffer Array [1..2048] Of Byte
- S_baReceiveBuffer Array [1..4096] Of Byte
(max. Buffer with compatibility mode: 1460 Byte)

 UDT1000 (saRequestStruct) DB201


- Number Request sArray ARRAY[1..20]
- Stringlength sData ARRAY[1..80]

 UDT1001 (saColumnNameStruct) DB202


- Number ColumnName sArray ARRAY[1..20]
- Stringlength sData ARRAY[1..20]

 UDT1002 (saTableValueStruct) DB203


- Number Rows/Columns sArray ARRAY[1..15,1..20]
- Stringlength sData ARRAY[1..20]

 UDT1003 (ConstVarStruct) DB200


- diMaxRows Number Datasets
- diMaxColumns Number Columns
- diStringLength Stringlength of Table Values
- diUBoundRequestArray Number of Request Elements
- diRequestStringLength Stringlength of Request Elements
- daDataBuffer Receive Buffer Size
The constants must be adjusted in accordance with the individual values!

139/208
Since the Communication Module of Siemens can only process a maximum data size of 8Kb, also the
SQL4Siemens Library can only send or receive a maximum of 8Kb (8192 Byte) in one step.

5.12.6 Table of Symbols

140/208
5.12.7 Ethernet-Interface Settings
In order to establish communication over the die Ethernet-Interface on the CPU and the Connector, it must
be parameterized. The IP address of the Ethernet-Interface must be in the same network address range as
the Ethernet-Interface of the Connector.

IP-Adresse der S7-Steuerung und die


Subnet-Maske eintragen

141/208
5.12.8 Configuring the Connector

With the Siemens-Target selected in the Connector, further options must be defined:

 Receive Buffer Size of the Receive Buffer in FB200


STAT: S_baReceiveBuffer ARRAY [1..4096] OF BYTE
 CP 343-1 Interface Deactivate
 Fix Buffer Deactivate

142/208
5.12.9 Sample Project

The sample project from the website is executable, and it should be set up first for execution, prior to
adapting your own application. This way, it is easier to detect possible sources for errors.

Only the IP address, the port and the Device-ID (see 5.12.2.1 Call FB200) must be adapted to your system
when calling FB200.

The connector must be started, and the connection to the sample database “S4A_Test_DB.mdb” must be
configured.
How to configure the connection to the test database is described under 4.1.1 Setting up the connection to
the test database.

For the test program FB10, the following blocks are additionally required:

• FB10, DB10 Test Block


• FC16 I_STRING, Integer to String Conversion
• SFC20 BLKMOV
• SFC21 FILL
• DB210 Data Block for Entering SQL Text
• DB220 Data Block for Displaying Values from the Database

The test block FB 10 which is called in OB1 contains a program sequence (step chain) which executes a
database request. FB 200 is also called on a cyclic basis in OB1. The input and output parameters of FB200 are
written and read in FB10.

143/208
5.12.9.1 Test Block FB10

5.12.9.1.1 FB10, Network 1

In Network 1, the step chain with the variable #IO_xFBReset (DB10.DBX 4.0) is reset.

5.12.9.1.2 FB10, Network 2

In Network 2 (Step 0 / #S_N00), the step chain with the variable #IO_xFBStart (DB10.DBX 1.0) is started.

144/208
5.12.9.1.3 FB10, Network 3

In Network 3 (Step 1 / #S_N01), the SQL command is compounded.

In the sample request, the following SQL command is sent to the Connector:
‘SELECT id, iParam1, fParam2, sText1 FROM tTable1 WHERE id<10 ORDER BY id DESC‘

Since the parameter ‘10‘is not expressed directly as text, but converted from an Integer value, the entire SQL
command must be compounded from three segments. Here, the Array Structure in DB201 can be used.

 The 1. Part of the request: ‘SELECT id, iParam1, fParam2, sText1 FROM tTable1 WHERE id<‘ is
copied into Array Index 1.
 The 2. Part of the request: ‘10‘ is copied into Array Index 2.
 The 3. Part of the request: ‘ ORDER BY id DESC‘ is copied into Array Index 3.

Upon sending the SQL command, FB200 compounds the contents of all Array Indices.

The fixed texts are defined in DB210.

Please note! An S7 string variable carries control characters in


the first two bytes.
The character string with the string contents starts from the
second byte onwards.

Therefore, the string variable must be copied into the saQuery-


Array upon database access.
Upon addressing, the source is shifted by 2 bytes each.

145/208
146/208
5.12.9.1.4 FB10, Network 4

In Network 4 (Step 2 / #S_N02), the SQL command is executed (#O_xExecute), and it is waited until the
request either resulted in an error (#I_xError), or was processed correctly (#I_xDone).

147/208
5.12.9.1.5 FB10, Network 5

In Network 5 (Step 3 / #S_N03), the received data in DB203 can be copied into variables (DB220) upon the
successful completion of the request.
In the following example, the first 8 values of DB203 are copied into the variables “Value_1_1”, “Value_1_2”,
“Value_1_3”, “Value_1_4”, “Value_2_1”, “Value_2_2”, “Value_2_3” and “Value_2_4”.

148/208
The DB220 is derived from UDT220, and defines the 8 variables of type CHAR Array.

The values can be viewed in DB220 in the observation


mode.

The values can also be viewed directly in the observation mode in DB203.

149/208
5.12.9.1.6 FB10, Network 6

In Network 6 (Step 4 / #S_N04), the step chain is reset, and a new request can be started.

5.12.9.2 Starting Test Block FB10

As soon as the complete sample project has been loaded, the step chain can be started in the observation
mode of FB10. In order to do so, the variable #IO_xFBStart (DB10.DBX 4.1) in the “Control” tab is set to 1 via
the context menu.

150/208
If the connection has been established successfully, the SQL command sent from the S7 will be visible in the
Config Tool.

The read-out values can be viewed in the observation mode in DB220.

151/208
5.12.10 Error Codes Return-Value
The variable “diResultState” describes the error.
Error Number Error Description
1 Unknown SQL Command
2 Request returns more datasets than defined by diMaxRows, modify request or increase diMaxRows
3 Request returns more columns than defined by diMaxColumns, modify request or increase diMaxColumns
4 Request returns more data than defined by buffer size
Modify request or increase Buf. Size in the Connector and in the application.
5 Request returns minimal one value that is bigger than defined by MaxStringLength, modify request or increasing
MaxStringLength
10 Internal Connector error
11 Internal Connector error, cannot open database
21 No IP-address defined
22 No port number defined
23 Request string is empty
24 Number MaxRows not defined
25 Number MaxColumns not defined
29 Size MaxStringLength not defined
41 No connection established to the SQL4automation-Connector (return value under parameter “diStatus”)
Error from block TCON. See 5.12.11 Status of Error Number 41
Turn off Firewall.
51 Error during sending of request (return value under parameter “diStatus”)
Error from block TSEND. See 5.12.12 Status of Error Number 51
61 Error during receipt of data (return value under parameter “diStatus”)
Error from block TRCV. See 5.12.13 Status of Error Number 61
71 Connection to the SQL4automation-Connector cannot be closed (return value under parameter “ diStatus”)
Error from block TDISCON. See 5.12.14 Status of Error Number 71
>100 Error numbers of the ODBC database connection (some known error numbers are attached)
40002 General error during SQL request, request string is invalid

152/208
5.12.11 Status of Error Number 41
- Connection establishment TCON

153/208
5.12.12 Status of Error Number 51
- Sending of data TSEND

154/208
5.12.13 Status of Error Number 61
- Receipt of data TRCV

155/208
5.12.14 Status of Error Number 71
- Connection termination TDISCON

156/208
5.13 S7-300 mit CP343 / SQL4Siemens SIMATIC Manager IL, Ladder – Target: “Siemens
S7”

5.13.1 Requirements
The communication functions on all S7-300 control systems with a CP communication processor.

The following blocks are required for the connection to the Connector:
• FB200 Function Block SQL4Siemens
• DB200 Instance Data Block SQL4Siemens
• DB201 Data Block S4A_saRequest (SQL Command Array)
• DB202 Data Block S4A_saColumnName (Column Names Array)
• DB203 Data Block S4A_saTableValue (Data Array)
• UDT1000 Structure S4A_saRequest (DB201)
• UDT1001 Structure S4A_saColumnName (DB202)
• UDT1002 Structure S4A_saTableValue (DB203)
• UDT1003 Structure S4A_saConstVarStruct (DB200)

• FC5 AG_SEND
• FC6 AG_RECV

157/208
5.13.2 Function Block (FB)

5.13.2.1 Call FB200


The FB200 is called on a cyclic basis, e.g. in OB1. The following parameters are configured:

 Local ID from the NetPro Configuration

Pointer anlegen für:


- saQuery (DB201)
- saColumnName (DB202)
- saTableValue (DB203)

158/208
5.13.2.2 Parameters of FB200

ID : INT; // Local ID from the NetPro Configuration.


See 5.13.7 Ethernet-Interface

xRestart : BOOL; // Restart CPU


xExecute : BOOL; // Start Database request
xAbort : BOOL; // Reset

timTimeOut : TIME; // Timeout in Seconds, Default 30s

ptRequest : ANY; // Pointer to saRequest (DB201)


ptColumnName : ANY; // Pointer to saColumnName (DB202)
ptTableValue : ANY; // Pointer to saTableValue (DB203)

xReady : BOOL; // Ready for Database request


xBusy : BOOL; // Database request in process
xDone : BOOL; // Database request completed
xError : BOOL; // Database request resulted in an Error

diResultState : DINT; // Status Database request / Error number


diResultRows : DINT; // Num. returned Rows from the Database request
diResultColumns : DINT; // Num. returned Columns from the Database request
wStatus : WORD; // Status of the S7 Modules AG_SEND, AG_RECV

5.13.3 Data Blocks (DB)


DB200 – Instance Data Block for internal use of Function Block SQL4Siemens (FB200).
DB201 – This Data Block contains the SQL Command to the SQL Database (Request).
DB202 – This Data Block contains the Column Names of the read-out Database Table (ColumnName).
DB203 – This Data Block contains the Data (Table Values) of the read-out Database Table (TableValue).
DB210 – This Data Block is only used in the Sample Program for easier entry of the SQL Command.
DB220 – This Data Block is only used in the Sample Program for read-out of the Database Values.

159/208
5.13.4 Data Types (UDT)
UDT1000 – Defines the Data Structure of DB201 (Size of SQL Command / Request)

UDT1001 – Defines the Data Structure of DB202 (Size of Columns Name / ColumnsName)

UDT1002 – Defines the Data Structure of DB203 (Size of Table Values / TableValues)

UDT1003 – Defines the Global Variables for Determining the Size of the various Tables.

160/208
5.13.5 Data Region
Some data types can be adjusted for project-specific purposes. Depending on the size of the data to be read
or written, the Array sizes or Data Type sizes are configured here.

 FB200
The size of the Send and Receive Buffer:
- S_baSendBuffer Array [1..2048] Of Byte
- S_baReceiveBuffer Array [1..4096] Of Byte
(max. Buffer with compatibility mode: 1460 Byte)

 UDT1000 (saRequestStruct) DB201


- Number Request sArray ARRAY[1..20]
- Stringlength sData ARRAY[1..80]

 UDT1001 (saColumnNameStruct) DB202


- Number ColumnName sArray ARRAY[1..20]
- Stringlength sData ARRAY[1..20]

 UDT1002 (saTableValueStruct) DB203


- Number Rows/Columns sArray ARRAY[1..15,1..20]
- Stringlength sData ARRAY[1..20]

 UDT1003 (ConstVarStruct) DB200


- diMaxRows Number Datasets
- diMaxColumns Number Columns
- diStringLength Stringlength of Table Values
- diUBoundRequestArray Number of Request Elements
- diRequestStringLength Stringlength of Request Elements
- daDataBuffer Receive Buffer Size
The constants must be adjusted in accordance with the individual values!

161/208
Since the Communication Module of Siemens can only process a maximum data size of 8Kb, also the
SQL4Siemens Library can only send or receive a maximum of 8Kb (8192 Byte) in one step.

5.13.6 Table of Symbols

162/208
5.13.7 Ethernet-Interface Settings
In order to establish communication between the CP communication processor and the Connector, the CP
must be parameterized.

5.13.7.1 IP Address of the CP Communication Processor


In the hardware configuration, the IP address of the CP communication processor can be configured. The IP
address of the CP Ethernet-Interface must be in the same network address range as the Ethernet-Interface of
the Connector.

IP-Adresse der CP und die


Subnet-Maske eintragen

163/208
5.13.7.2 IP Address of the Connector
In the menu “Options” – “Configure Network” of the SIMATIC Manager, the NetPro Configuration can be
opened.

In the “Addresses” tab, the IP address and the port of the Connector is entered (Partner). The IP address of
the CP Ethernet-Interface must be in the same network address range as the Connector Ethernet-Interface.

164/208
5.13.8 Configuring the Connector

With the Siemens-Target selected in the Connector, further options must be configured:

 Receive Buffer Size of the Receive Buffer in FB200


STAT: S_baReceiveBuffer ARRAY [1..4096] OF BYTE
 CP 343-1 Interface Activate
 Fix Buffer Activate

165/208
5.13.9 Sample Project

The sample project from the website is executable, and it should be set up first for execution, prior to
adapting your own application. This way, it is easier to detect possible sources for errors.

Only the IP address, the port and the Device-ID (see 5.13.7.2 IP Address of the Connector) and the Local ID
(see 5.13.2.1 Call FB200) must be adapted to your system when calling FB200.

The connector must be started, and the connection to the sample database “S4A_Test_DB.mdb” must be
configured.
How to configure the connection to the test database is described under 4.1.1 Setting up the connection to
the test database.

For the test program FB10, the following blocks are additionally required:

• FB10, DB10 Test Block


• FC16 I_STRING, Integer to String Conversion
• SFC20 BLKMOV
• SFC21 FILL
• DB210 Data Block for Entering SQL Text
• DB220 Data Block for Displaying Values from the Database

The test block FB 10 which is called in OB1 contains a program sequence (step chain) which executes a
database request. FB200 is also called in OB1 on a cyclic basis. The input and output parameters of FB200 are
written and read in FB10.

166/208
Test block FB10

5.13.9.1.1 FB10, Network 1

In Network 1, the step chain with the variable #IO_xFBReset (DB10.DBX 4.0) is reset.

5.13.9.1.2 FB10, Network 2

In Network 2 (Step 0 / #S_N00), the step chain with the variable #IO_xFBStart (DB10.DBX 4.0) is started, and

167/208
5.13.9.1.3 FB10, Network 3

In Network 3 (Step 1 / #S_N01), the SQL command is compounded.

In the sample request, the following SQL command is sent to the Connector:
‘SELECT id, iParam1, fParam2, sText1 FROM tTable1 WHERE id<10 ORDER BY id DESC‘

Since the parameter ‘10‘is not expressed directly as text, but converted from an Integer value, the entire SQL
command must be compounded from three segments. Here, the Array Structure in DB201 can be used.

 The 1. Part of the request: ‘SELECT id, iParam1, fParam2, sText1 FROM tTable1 WHERE id<‘ is
copied into Array Index 1.
 The 2. Part of the request: ‘10‘is copied into Array Index 2.
 The 3. Part of the request: ‘ ORDER BY id DESC‘is copied into Array Index 3.

Upon sending the SQL command, FB200 compounds the contents of all Array Indices.

The fixed texts are defined in DB210.

Please note! An S7 string variable carries control characters in


the first two bytes.
The character string with the string contents starts from the
second byte onwards.

Therefore, the string variable must be copied into the saQuery-


Array upon database access.
Upon addressing, the source is shifted by 2 bytes each.

168/208
169/208
5.13.9.1.4 FB10, Network 4

In Network 4 (Step 2 / #S_N02), the SQL command is executed (#O_xExecute), and it is waited until the
request either resulted in an error (#I_xError), or was processed correctly (#I_xDone).

170/208
5.13.9.1.5 FB10, Network 5

In Network 5 (Step 3 / #S_N03) the received data in DB203 can be copied into variables (DB220) upon the
successful completion of the request
n the following example, the first 8 values of DB203 are copied into the variables “Value_1_1”, “Value_1_2”,
“Value_1_3”, “Value_1_4”, “Value_2_1”, “Value_2_2”, “Value_2_3” and “Value_2_4”.

171/208
The DB220 is derived from UDT220, and defines the 8 variables of type CHAR Array.

The values can be viewed in DB220 in the observation


mode.

The values can also be viewed directly in the observation mode in DB2203.

172/208
5.13.9.1.6 FB10, Network 6

In Network 6 (Step 4 / #S_N04), the step chain is reset, and a new request can be started.

5.7.9.2 Starting Test Block FB10

As soon as the complete sample project has been loaded, the step chain can be started in the observation
mode of FB10.
In order to do so, the variable #IO_xFBStart (DB10.DBX 4.1) in the “Control” tab is set to 1 via the context
menu.

173/208
If the connection has been established successfully, the SQL command sent from the S7 will be visible in the
Config Tool.

In the case of an Ethernet connection with a CP communication processor, the connection remains open. This
is indicated by the colour state of the active link. Blue means that the connection is active. The activated
CP343 option in the link settings has the effect that no timeout is triggered.

The read-out values can be viewed in the observation mode in DB220.

174/208
5.13.10 Error Codes Return-Value
The variable “diResultState” describes the error.
Error Number Error Description
1 Unknown SQL Command
2 Request returns more datasets than defined by diMaxRows, modify request or increase diMaxRows
3 Request returns more columns than defined by diMaxColumns, modify request or increase diMaxColumns
4 Request returns more data than defined by buffer size
Modify request or increase Buf. Size in the Connector and in the application.
5 Request returns minimal one value that is bigger than defined by MaxStringLength, modify request or increasing
MaxStringLength
10 Internal Connector error
11 Internal Connector error, cannot open database
21 No IP-address defined
22 No port number defined
23 Request string is empty
24 Number MaxRows not defined
25 Number MaxColumns not defined
29 Size MaxStringLength not defined
41 No connection established to the SQL4automation-Connector (return value under parameter “diStatus”)
Error from block TCON. See 5.13.11 Status of Error Number 41
Turn off Firewall.
51 Error during sending of request (return value under parameter “diStatus”)
Error from block TSEND. 5.13.12Status of Error Number 51
61 Error during receipt of data (return value under parameter “diStatus”)
Error from block TRCV. See 5.13.13Status of Error Number 61
71 Connection to the SQL4automation-Connector cannot be closed (return value under parameter “ diStatus”)
Error from block TDISCON. See 5.13.14Status of Error Number 71
>100 Error numbers of the ODBC database connection (some known error numbers are attached)
40002 General error during SQL request, request string is invalid

175/208
5.13.11 Status of Error Number 41
- Connection establishment TCON

176/208
5.13.12 Status of Error Number 51
- Sending of data TSEND

177/208
5.13.13 Status of Error Number 61
- Receipt of data TRCV

178/208
5.13.14 Status of Error Number 71
- Connection termination TDISCON

179/208
5.14 SQL4Siemens / S7-400 CP443 SIMATIC Manager IL, Ladder – Target: “Siemens S7”

Communication also functions with all S7-400 control systems with a CP communication processor CP443.
However, some changes are required, as the communication blocks FC5 and FC6 do not function correctly on
the CP443. For correction, please replace the FC5 with FC50, and the FC6 with FC60.

Also, the FC50 will create an error code 7000 on the S7-400, when it is called for the first time. As a result of
this, the following changes must be made in FB200:

For other issues, the documentation of CP343 is applicable.

180/208
5.15 Allen Bradley, Rockwell / SQL4RSLogix – Target: „Standard“

5.15.1 Requirements
The Add-On “SQL4automation” uses an Ethernet/IP socket connection to the Connector. For this reason, the
control system must support Ethernet/IP sockets. The following Ethernet communication modules support
Ethernet/IP sockets: 1756-EWEB, 1756-EN2Txx, 1768-EWEB (CompactLogix). Also, control systems can be
used which feature an integrated Ethernet/IP interface on the CPU.
The sample projects are devised for the controller 1756-L63 ControlLogix5563, and for a 1769-L18ER-BB1B
CompactLogix5318ERM-BB1B. However, these sample projects can be easily adapted to other controller
types by simply changing the controller. For a ControlLogix, use the ControlLogix example, for a
CompactLogix, use the CompactLogix example.
If you already have an existing project, you can carry out the steps described in the following sections.
Otherwise, you can immediately open a finished project “5.15.9 Sample Project”.

5.15.2 Importing Add-On and Tags


The Add-On “SQL4automation” can be imported using the import function “Import Add-On Instruction…”
(right mouse button: Controller Organizer - Add-On Instructions)
(AddOn_SQL4automation_v2.x.x.x.L5X).
Additionally, the missing tags can be added via menu “Tool – Import – Tags and Comments…”
(Sample_S4A_CxxxxxxLogix_xxxxxxx-Controller-Tags and
Sample_S4A_CxxxxxLogix_xxxxxxx-MainProgram-Tags).

5.15.3 Add-On (Function Block)

181/208
5.15.4 Data Types
Some data types can be adjusted for project-specific purposes. Depending on the size of the data to be read
or written, the Array sizes or Data Type sizes are configured here.
STRING – Data Types

STRING_READBUFFER Maximum Characters: 484 // The maximum TCP Read-Buffer is dependent on


the Control system type.
STRING_WRITEBUFFER Maximum Characters: 462 // The maximum TCP Write-Buffer is dependent
on the Control system type.
STRING_READBUFFER_COMPLETE Maximum Characters: 5000 // The maximum size of the data to read
(SQL data).
STRING_WRITEBUFFER_COMPLETE Maximum Characters: 1000 // The maximum size of the data to write
(SQL query)
STRING_REQUEST Maximum Characters: 100 // The maximum String-Length in the Request-
Array (per Index)
STRING_VALUE Maximum Characters: 20 // The maximum String-Length in the
TableValue-Array (per Value)

Attention ControlLogix control systems can only communicate with Unconnected connections, whereas
ControlLogix control systems can also establish Connected connections, i.e. Standard
connections.
The table shows the buffer sizes (STRING_READBUFFER, STRING_WRITEBUFFER) of the different
connection types.

Large Connection Size are supported only by 1756-EN2xx ControlLogix modules in RSLogix 5000
software, version 20 or later.

From Add-On V2 release (AddOn_SQL4automation_v2.0.0.0.L5X) the partial reading and writing is


supported. This also enables the transmission of large amounts of data, even if the TCP buffers are less
than to read or write the data.

182/208
The String-Data Types must be adjusted in the Controller Organizer under Data Types – Configure Strings.

183/208
USER DEFINED – Data Types

REQUEST STRING_REQUEST[10] // The Array-Size of the Request-Array (Index)


COLUMN STRING_VALUE[25] // The Array-Size of the TableValue-Array (Number of
Columns)
VALUE COLUMN[50] // The Array-Size of the TableValue-Array (Number of Rows)

Note: By adjusting the size of the Data Types REQUEST, COLUMN and VALUE, the required memory size
can be adjusted to the respective application.

The User-Defined-Data Types must be configured in the Controller Organizer under Data Types – User-
Defined.

Besides the Data Types REQUEST, COLUMN and VALUE, the following Data Types are required for the Socket
communication: SOCK_Addr, SOCK:CreateParams, SOCK_DATA_CLIENT, SOCK_OpenConnParam,
SOCK_ReadParams, SOCK_ReadResponse, SOCK_WriteParams. However, these must not be adjusted.

184/208
5.15.5 Tags

Controller-Tags

For the Socket communication and to call the Function Blocks, the following Controller-Tags are required.

Client_DATA SOCK_DATA_CLIENT // Manages the Socket-Data


Connect_MSG MESSAGE // MESSAGE Function: Connect Socket
Create_MSG MESSAGE // MESSAGE Function: Create Socket
Delete_All_MSG MESSAGE // MESSAGE Function: Delete all Sockets
Delete_MSG MESSAGE // MESSAGE Function: Delete Socket
Read_MSG MESSAGE // MESSAGE Function: Read from Socket
Write_MSG MESSAGE // MESSAGE Function: Write to Socket

Note: The MESSAGE function applies to several Socket functions


Depending on the type of hardware used, the options Connected, Cache Connection or Large
Connection must be configured differently. For instance, ControlLogix control systems can only
be used in conjunction with Unconnected connections, and ControlLogix control systems only
with Connected connections.

185/208
Program-Tags

For the Function Block call, the following Program-Tags are required.
saRequest REQUEST // Request-Array
saTableValue VALUES // TableValue-Array
EWEB_PATH STRING // Ethernet-Module Slot. E.g. Backplane 1, Slot 3 = ‘$01$03‘
sDestination STRING // Dest. of the Connector. E.g. ‘192.168.1.202 ?port=11001’
SQL4RSLogix SQL4automation // Instance of the Function Block

186/208
5.15.6 Parameters SQL4automation Function Block
The instance of the SQL4automation Function Block requires the following input and output parameters.

SQL4RSLogix SQL4automation // Instance of the SQL4automation Function Block

INOUT-Parameter

saRequest REQUEST // Request-Array


saTableValue VALUES // TableValue-Array
saColumnName COLUMN // Column names
sDestination STRING // Dest. of the Connector. E.g. ‘192.168.1.202 ?port=11001’
EWEB_PATH STRING // Ethernet-Modul Slot. E.g. Backplane 1, Slot 3 = ‘$01$03‘
Client_DATA SOCK_DATA_CLIENT // Manages the Socket-Data
Connect_MSG MESSAGE // MESSAGE Function: Connect Socket
Create_MSG MESSAGE // MESSAGE Function: Create Socket
Delete_All_MSG MESSAGE // MESSAGE Function: Delete all Sockets
Delete_MSG MESSAGE // MESSAGE Function: Delete Socket
Read_MSG MESSAGE // MESSAGE Function: Read from Socket
Write_MSG MESSAGE // MESSAGE Function: Write to Socket

INPUT-Parameter

xExecute BOOL; // Start Database request


xAbort BOOL; // Reset
xHoldConnection BOOL; // Holds the Socket connection open after a Database
request
xReadNoColumnNames BOOL; // Does not read the coulmn names
iLocalPort INT // Port number of the Control system. 0=default
diTimeout DINT // Timeout of a request [ms]

OUTPUT-Parameter

xReady BOOL // Ready for Database request


xBusy BOOL // Database request in process
xDone BOOL // Database request completed
xError BOOL // Database request resulted in an Error
diResultState DINT // Status Database request / Error number
diResultRows DINT // Number of returned rows from the Database request
diResultColumns DINT // Number of returned columns from the Database request
diStep DINT // Internal Step

187/208
5.15.7 Handshake
The handshake is conducted in accordance with the handshake of the StandardProtocol. The
StandardProtocol is described under 6.1 Standard Protocol.

5.15.8 Error Codes Return-Value


The variable “diResultState” describes the error.
Error Number Error Description

1 Unknown SQL Command


2 Request returns more datasets than defined by gc_diMaxRows, modify request or increase gc_diMaxRows
3 Request returns more columns than defined by gc_diMaxColumns, modify request or increase gc_diMaxColumns
4 Request returns more data than the defined buffer size.
Modify request or increase STRING_READBUFFER_COMPLETE.
5 Request returns minimal one value that is bigger than defined by MaxStringLength, modify request or increase
MaxStringLength
10 Internal Connector error
11 Internal Connector error, cannot open database
22 No target address defined for Connector / sDestination=’’
23 Request string is empty
24 Number MaxRows not defined
25 Number MaxColumns not defined
29 Size MaxStringLength not defined
40 Error during creation of socket. No connection to SQL4automation-Connector established.
Turn off Firewall.
41 Error during connection to the SQL4automation-Connector.
Turn off Firewall.
50 Sending the complete request string has failed. Please check your connection or the TCP buffer of your system.
51 Request string is greater than the send buffer.
61 Error during data reading from the SQL4automation-Connector. Possible cause, too much data.
62 Error during data reading from the SQL4automation-Connector. Increase STRING_READBUFFER_COMPLETE.
Please update the SQL4automation Connector (from V3.4.1.0 -> new error number: 4)
71 Error during closing the connection to the SQL4automation-Connector
99 Timeout
>100 Error numbers of the ODBC database connection (some known error numbers are attached)
40002 General error during SQL request, request string is invalid

188/208
5.15.9 Sample Project
As a sample project, a project was created which is completely executable. There are four variations. One
example is for a ControlLogix, the other one for a CompactLogix control system. Both versions are available in
the programming language Ladder and Stuctured Text.
The sample projects are devised for the controller 1756-L63 ControlLogix5563 and for a 1769-L18ER-BB1B
CompactLogix5318ERM-BB1B. However, these sample projects can be easily adapted to other controller
types by simply changing the controller. For a ControlLogix, use the ControlLogix example, for a
CompactLogix, use the CompactLogix example.
The four sample projects are named:
Sample_S4A_CompactLogix_Ladder.ACD
Sample_S4A_CompactLogix_StructuredText.ACD
Sample_S4A_ControlLogix_Ladder.ACD
Sample_S4A_ControlLogix_StructuredText.ACD

Note: When executing the database request, the test license has to be activatet by the „S4A
Config“ tool and a Link must be configured (with port number e.g. 11001) to the test
database “S4A_Test_DB.mdb”.
How to configure the connection to the test database is described under 4.1.1 Setting up
the connection to the test database.

189/208
By writing xExecute, the program can be tested. In the case of an error, the connection can be reset by
writing xAbort. After each successful request, the request-string from saRequest_Temp must be copied to
saRequest.

By setting the variable xStart to 1, an automated execution of a database request can be performed. Reset
xStart to 0 after the the request is done.
By setting the variable xLoop also to 1, the database query is carried out continuously.
All queries are logged in the "S4A Debugger" tool.

190/208
5.16 Sigmatek / SQL4LASAL – Target: “Standard“ / “UTF16”

5.16.1 Requirements

All Sigmatek controls which support an open TCP/IP communication may be connected to SQL4automation.
The library has been tested with the SoftSPS Lars and a C-IPC.

5.16.2 The classes

The sample project includes two classes. One class communicates with the SQL4automation Connector via
UTF-8, the other via UTF-16. In case the UTF-8 class is used the “standard” target has to be selected in the
Connector, for the UTF-16 the “UTF-16” target has to be selected.

191/208
5.16.3 Servers
The classes SQL4LASAL include the following servers:
xAbort :DINT // Reset
xBusy :DINT // Database query is running
xDone :DINT // Database query completed
xError :DINT // Database query ended with an error
xHoldConnection :DINT // Keeps the socket connection open after a database query
ErrorCode_Sigmatek :DINT // Sigmatek specific error code
diResultState :DINT // Status database query / error number
diResultRows :DINT // Number of received rows from the database query
diResultColumns :DINT // Number of received columns from the database query
C_IP_Adr_1 :UDINT // Configured IP address of the SQL4automation-Connectors position1
C_IP_Adr_2 :UDINT // Configured IP address of the SQL4automation-Connectors position2
C_IP_Adr_3 :UDINT // Configured IP address of the SQL4automation-Connectors position3
C_IP_Adr_4 :UDINT // Configured IP address of the SQL4automation-Connectors position4
C_iPort :UDINT // Configured port number of the SQL4automation-Connectors
C_TimeOut :UDINT // Timeout

5.16.4 Methods

5.16.4.1 SendRequest
This method is used for the SQL request.
VAR_INPUT
pRequest : ^UINT; // Pointer request string
pColumnsName : ^UINT; // Pointer column name
pTableValues : ^UINT; // Pointer results table
NumberOfRows : UINT; // Number of received rows from the database query
NumberOfColumns : UINT; // Number of received columns from the database
query
SizeOfOneFieldInByte : UINT; // String length in the table array
pSQL4AutomationControl : ^SQL4AUTOMATION_CONTROL_TYPE; // Pointer return value status request
HoldConnection : BOOL; // Hold connection
END_VAR
VAR_OUTPUT
result : INT; //Return value of the method
END_VAR

5.16.4.2 FormatString

This method may be used for the conversion of strings to SQL requests.
VAR_INPUT
pDestination : ^UINT; // Pointer to output string
pSource : ^UINT; // Pointer to input string
Trim : BOOL; // Avoid space at the beginning and at the end
MaxSizeInByte : UDINT; // Maximum number of characters
END_VAR
VAR_OUTPUT
StrLng : UINT;
END_VAR

192/208
5.16.4.3 FormatDateTime
This method may be used for the conversion of DateTime types to SQL requests.
VAR_INPUT
pDestination : ^UINT; // Pointer to output string
pDate : ^_DATE; // Pointer to input date
pTime : ^_TIME; // Pointer to input time
MaxSizeInByte : UDINT; // Maximum number characters
END_VAR

5.16.5 Sample project SQL4LASALSample

The sample project shows how the classes SQL4LASALASCII and SQL4LASALUCS2 are applied. The sample
project is preconfigured in such a way that it runs on a SoftSPS Lars, SQL4automation Connector and Access
database on the same PC. Three links have to be still created with the Config Tool.
Link 1: Target Type: Standard, Connector IP: localhost, Port 11001, data source: ODBC connection to Access
database. (Is used for the connection Net ASCII)
Link 2: Target Type: UTF-16, Connector IP: localhost, Port 11002, data source: ODBC connection to Access
database. (Is used for NET UNICODE)
Link 3: Target Type: Standard, Connector IP: localhost, Port 11003, data source: ODBC connection to Access
database. (Is used for NET Cyclic)
The connector has to be started and the connection to the sample database “S4A_Test_DB.mdb” has to be
configured.
How to configure the connection to the test database is described under 4.1.1 Setting up the connection to
the test database.
.

5.16.5.1 NET ASCII


This example shows how a UTF-8 connection to the SQL4automation is established. The following options
may be set: database type: 0=example database MS Access, 1=MySQL, 2=MS SQL server, SendRequest: -1=
SELECT command, 0=create new table (only MySQL and MS SQL server), 1 = INSERT command.

193/208
5.16.5.2 NET UNICODE
This example shows how a UTF-16 connection to the SQL4automation is established. The following options
may be set: database type: 0=example database MS Access, 1=MySQL, 2=MS SQL server, SendRequest: -1=
SELECT command, 0=create new table (only MySQL and MS SQL Server), 1 = INSERT command.

5.16.5.3 NET Cyclic


This example shows how data can be written into the database cyclically and should also illustrate the
performance of the Sigmatek controls in connection with SQL4automation. Options: diStart >0:INSERT
commands are executed.

5.16.5.4 Adjustments Hardware SPS


In case a hardware SPS is used, the IP of the network card which is connected to the control has to be
selected in the link settings under Connector IP. The same IP also has to be selected for the SQL4LASA_ASCII
and SQL4LASAL_UCS2 instances under NET.

194/208
5.17 ABB AC500 / SQL4AC500 – Target: “Standard”
The SQL4AC500-Library functions with the PLC AC500 from the company Firma ABB. In terms of the Socket
connection, this library only differs slightly from the SQL4CoDeSys-Library. The implementation and the
operation are identical. Please use the instructions of CODESYS V2.3 (chapter 5.1 CODESYS V2.3 /
SQL4CODESYS – Target: „Standard“”).

The sample project (ABB-AC500-SQL4ABB.project) is opened with the ABB Configurator.

195/208
5.18 ABB Robotics / SQL4Rapid – Target: “Standard”
SQL4Rapid consists of two program modules. SQL4Rapid, the actual module block which establishes the
connection to the SQL4automation Connector, and main1, the example for how to integrate the SQL4Rapid
program module.

5.18.1 Requirements
The Robot control system or the Offline system must be equipped with the following options:
841-1 EtherNet /IP M/S

616-1 PC Interface.

5.18.2 Variables to be defined


LOCAL CONST num nMaxRows:=50; ! max Number of Datasets, from Table-Array
LOCAL CONST num nMaxColumns:=20; ! max Number of Columns, from Table-Array
LOCAL VAR string strTableValues{nMaxRows,nMaxColumns}; ! Table of results
LOCAL VAR string strColumnsName{nMaxColumns}; ! Column names
LOCAL CONST num nBoundRequestArray:=10; ! Maximum Index of the Request_String-Array
LOCAL VAR string strRequest{nBoundRequestArray}; ! Request-String-Array
LOCAL VAR num nResultState; ! Status / Error message of request
LOCAL VAR num nResultRows; ! Number of received Datasets
LOCAL VAR num nResultColumns; ! Number of received Columns
LOCAL VAR string strIP:="127.0.0.1"; ! IP address of the Connector
LOCAL VAR num nPort:=11001; ! Port of the connection
LOCAL VAR bool xHoldConnection; ! Holds the connection open between several
queries.
LOCAL VAR socketdev Socket; Socket for the connection

196/208
5.18.3 Executing the Sample Project
Under Control – Create System, create a new system with the options 840-1 EtherNet /IP M/S and 616-1 PC
Interface. Create a new station, and select the created system.

Under Control – Program module, add the modules “main1” and “SQL4Rapid”.

Configure the SQL4automation Connector as described in 3 Configuring the SQL4automation Connector


and configure the connection to the S4A_Test_DB.mdb. How to configure the connection to the test
database is described under 4.1.1 Setting up the connection to the test database.

197/208
Under Simulation, the program execution is started.

198/208
5.19 KUKA / SQL4KUKA – Target: “KUKA”
SQL4KUKA consists of sql4kuka.xml, the configuration file for the Ethernet XML communication, sql4kuka.src
/ sql4kuka.dat, the library for connection to the SQL4automation Connector and the example.src /
example.dat, the sample program.

5.19.1 Requirements
SQL4KUKA is possible from the KRC4 control system and up, and is established via the Ethernet KRL XML
Interface, which is available from KUKA as an option.

5.19.2 Installing the Interface

In order to install the interface, the HMI must be minimized and the EKI Network Editor must be started.
For minimizing the HMI, the user must be logged in as Expert. Via Robot – Setup – Service – Minimize HMI,
the user gets to the Windows environment of the SMARTPAD.
Under Start - EKI-Network, the EKI Network Editor is started.

In the EKI Network Editor, the local IP of the TCP/IP connection is configured.
Highlight the entry New, and edit with Edit.

Enter the local IP, and confirm by clicking OK.

199/208
To apply the changes, the control system must be restarted with the option “Apply changes upon cold boot”.

In the sql4kuka.xml, the IP and the port of the Connector are configured:

sql4kuka.xml

Sql4kuka.dat

For the communication with the library, 7 free digital output ports are required. These must correspond with
each other in the sql4kuka.xml, and the sql4kuka.dat.
The file sql4kuka.xml must be located under \krc\roboter\config\user\common\EthernetKRL, example.src,
example.dat, and the folder sql4kuka must be copied to directory \krc\roboter\krc\r1\program.
After a cold reboot, the sample can be tested.

200/208
5.19.3 Help Functions SQL4KUKA
The library sql4kuka.src offers many useful help functions for the copying of values and the compounding of
strings.

Creating a new Request String


EXTFCT BOOL NewRequest(CHAR[]:OUT, CHAR[]:IN)

Adding a BOOL to the Request String


EXTFCT BOOL BOOL_To_Request(CHAR[]:OUT, BOOL:IN)

Adding an INT to the Request String


EXTFCT BOOL INT_To_Request(CHAR[]:OUT, INT:IN)

Adding a REAL to the Request String


EXTFCT BOOL REAL_To_Request(CHAR[]:OUT, REAL:IN)

Adding a CHAR to the Request String


EXTFCT BOOL CHAR_To_Request(CHAR[]:OUT, CHAR:IN)

Adding a STRING to the Request String


EXTFCT BOOL STRING_To_Request(CHAR[]:OUT, CHAR[]:IN)

Converting a Value from the Return Table into a BOOL


EXTFCT BOOL Table_To_BOOL(INT:IN, INT:IN, BOOL:OUT)

Converting a Value from the Return Table into an INT


EXTFCT BOOL Table_To_INT(INT:IN, INT:IN, INT:OUT)

Converting a Value from the Return Table into a REAL


EXTFCT BOOL Table_To_REAL(INT:IN, INT:IN, REAL:OUT)

Converting a Value from the Return Table into a CHAR


EXTFCT BOOL Table_To_CHAR(INT:IN, INT:IN, CHAR:OUT)

Converting a Value from the Return Table into a STRING


EXTFCT BOOL Table_To_STRING(INT:IN, INT:IN, CHAR[]:OUT)

201/208
5.20 B&R / SQL4BR – Target: “Standard”

5.20.1 Requirements
 B&R Automation Studio V3.0.80.25 or higher
 Automation Runtime V3.00 or higher

5.20.2 Implementing the Library into the B&R Automation Studio


To implement the library into the B6R Automation Studio, it must be copied into the Library directory of
Automation Studio. Per default, this directory is located under: C:\Programme\BrAutomation\AS\Library

5.20.3 Integrating the SQL4BR Library into the Application Program


After a new project has been created, the SQL4BR library must be added to the project. The libraries AsTCP,
asstring and standard are automatically integrated.

5.20.4 Global Variables


VAR CONSTANT
diUBoundRequestArray : DINT := 5; (* UpperBoundary Request-String-Array, must be attributed the same value as
diUBoundRequestArray of the Library*)
diRequestStringLength : DINT := 256; (* String-Length Request-String-Array, must be attributed the same value as
diRequestStringLength of the Library *)
END_VAR
VAR
saRequest : ARRAY[1..diUBoundRequestArray] OF STRING[diRequestStringLength]; (* Request String Array *)
END_VAR

5.20.5 Instance / Interface


The following Variables can be configured in the file SQL4BR.var:
VAR CONSTANT
diMaxRows : DINT := 50; (* max Number Datasets, from Table-Array *)
diMaxColumns : DINT := 15; (* max Number Columns, from Table-Array *)
diStringLength : DINT := 256; (* String-Length in the Table-Array *)
diUBoundRequestArray : DINT := 5; (* UpperBoundary Request-String-Array *)
diRequestStringLength : DINT := 256; (* String-Length Request-String-Array *)
diReadDataBuffer : DINT := 1024; (* Databuffer for Reading the Data *)
diWriteDataBuffer : DINT := 1024; (* Databuffer for Writing the Data *)
END_VAR

The SQL4BR contains the following input and output variables:


VAR_INPUT
xExecute : BOOL; (* Executing the SQL Request *)
xAbort : BOOL; (* Reset *)
sIPAddressPLC : STRING[15]; (* IP address of the PLC *)
sIPAddressCon : STRING[15]; (* IP address of the Connector *)
iPort : INT; (* Port Number of the SQL4automation-Connectors *)
xHoldConnection :BOOL; (* Hold connection to the Connector *)
timTimeOut :TIME; (* Timeout in Seconds, Default 30s *)
saRequest : ARRAY[1..diUBoundRequestArray] OF STRING[diRequestStringLength]; (* SQL Request String-Array *)
END_VAR

202/208
VAR_OUTPUT
xReady : BOOL; (* Ready for SQL Request *)
xBusy : BOOL; (* SQL Request in process *)
xDone : BOOL; (* SQL Request completed *)
xError : BOOL; (* SQL Request resulted in an Error *)
diResultState : DINT; (* Status of result / Error number *)
diResultRows : DINT; (* Number Result-Datasets *)
diResultColumns :DINT; (* Number Result-Columns *)
saColumnsName : ARRAY[1..diMaxColumns] OF STRING[diStringLength]; (* Column names*)
saTableValues : ARRAY[1..diMaxRows,1..diMaxColumns] OF STRING[diStringLength]; (* Data-Array*)
diCycle : DINT; (* Cycle-Time *)
END_VAR

5.20.6 Creating an Instance


Creating an instance of the SQL4BR library and local variables.
VAR
SQL4automation : SQL4BR;
xExecute: BOOL;
xAbort: BOOL;
sIPAddressPLC: STRING[15]:='127.0.0.1';
sIPAddressCON: STRING[15]:='127.0.0.1';
iPort: INT := 11001;
xHoldConnection: BOOL := FALSE;
timTimeOut: TIME := T#30s;
xReady: BOOL;
xBusy: BOOL;
xDone: BOOL;
xError: BOOL;
diResultState: DINT;
diResultRows: DINT;
diResultColumns: DINT;
diCycle : DINT;
sAnswerSample : STRING[diRequestStringLength];
END_VAR

5.20.7 Error Codes Return-Value


The variable “diResultState” describes the error.
Error Number Error Description
1 Unknown SQL Command
2 Request returns more datasets than defined by MaxRows, modify request or increase MaxRows
3 Request returns more columns than defined by MaxColumns, modify request or increase MaxColumns
5 Request returns minimal one value that is bigger than defined by MaxStringLength, modify request or increase
MaxStringLength
10 Internal Connector error
11 Internal Connector error, cannot open database
21 No IP address PLC and/oder Connector defined
22 No port number defined
23 Request string is empty
24 Number MaxRows not defined
25 Number MaxColumns not defined
29 Size MaxStringLength not defined
41 Error during opening the Control system port
42 No connection to SQL4automation-Connector established. Turn off Firewall.
51 Error during sending of request
71 Connection to the SQL4automation-Connector cannot be closed
99 Timeout
>100 Error numbers of the ODBC database connection (some known error numbers are attached)
40002 General error during SQL request, request string is invalid

203/208
5.20.8 Sample Project SQL4BRSample
The SQL4BR Library has already been integrated into the sample project SQL4BRSample. The project can be
tested on the Soft PLC AR000 which is contained in B&R Automation Studio. The connector must be started,
and the connection to the sample library “S4A_Test_DB.mdb” must be configured.
How to configure the connection to the test database is described under 4.1.1 Setting up the connection to
the test database.

By forcing xExecute, the program can be tested. In the case of an error, the connection can be reset by
forcing xAbort.

204/208
6 TLP – Target-Link-Protocol
In case there is no library available yet for your control system, you can emulate the protocol between
control system and Connector by referring to the following documentation. Please contact us first in this
case, as we are continuously developing libraries for additional control systems.

6.1 Standard Protocol


With each SQL request to the database, the Connector is provided with information prior to execution.

6.1.1 Request to the Connector


Attribute Data Type Description Default
MR Null-terminated String Max Rows
<MR Value> Null-terminated String Minimum 1 Not optional
MC Null-terminated String Max Columns
<MC Value> Null-terminated String Minimum 1 Not optional
MS Null-terminated String Max String
<MS Value> Null-terminated String Minimum 1 Not optional
CT Null-terminated String Connector Timeout
<CT Value> Null-terminated String 0 = no Timeout, Connection remains open, >0 = Timeout in seconds Not active
CN Null-terminated String Column Names
<CN Value> Null-terminated String 0 = no Column names, 1 = Column names (default 1) 1
CS Null-terminated String Cut String
<CS Value> Null-terminated String String of each value is shortened to length CS Not active
S Null-terminated String String (SQL Request)
<S Value> Null-terminated String Minimum 1 character Not optional
T Null-terminated String Transmit Request

<MR><NUL><MR Value><NUL> Maximum number of datasets which can be stored in the control system
<MC><NUL><MC Value><NUL> Maximum number of columns which can be stored in the control system
<MS><NUL><MS Value><NUL> Length of the string variable in the control system
<CT><NUL><CT Value><NUL> Timeout Connector (optional)
<CN><NUL><CN Value><NUL> A database request also returns the column names in addition to the data, or not. (optional)
<CS><NUL><CS Value><NUL> A database request also returns data if the size of the database value exceeds the defined
maximum string length (MS). The value will be cut off after the CS value, and the error is ignored.
(optional)
<S><NUL><S Value><NUL> SQL request string
<S><NUL><S Value><NUL> If the SQL request string is too large for the control system, it can be sent to the connector in a dissected
form. (optional)
<T><NUL> Start command to send the SQL request string to the database

Examples:
MRNUL80NULMCNUL40NULMSNUL255NULSNULSELECT id, iParam1, fParam2, sText1 FROM tTable1NULTNUL

MRNUL80NULMCNUL40NULMSNUL255NULCS NUL80NULCNNUL0NUL
SNULSELECT id, iParam1, fParam2, sText1 FROM tTable1NUL
SNULWHERE id < 4NUL
TNUL

205/208
6.1.2 Response from the Connector
Attribute Data Type Description
RS Null-terminated String Return State
<RS Value> Null-terminated String
RR Null-terminated String Result Rows
< RR Value> Null-terminated String
RC Null-terminated String Result Columns
< RC Value> Null-terminated String
RN Null-terminated String Result Column names
< RN Values> Null-terminated String
RD Null-terminated String Result Data
< RD Values> Null-terminated String

<RS><NUL><RS Value><NUL> RS Value = 0 Okay, data will follow


RS Value > 0 Error code, no data will follow
Bei RS Value = 0
<RR><NUL><RR Value><NUL> RR Value Number datasets
<RC><NUL><RC Value><NUL> RC Value Number columns

If RC Value > 0 data will follow, else RR Value contains the number of the processed datasets (Update,
Delete…)

<RN><NUL> RN followed by all column names


For iC = 1 to RC
<RN Value[iC]> <NUL>
Next iC

<RD><NUL> RD followed by all data


For iR = 1 to RR
For iC = 1 to RC
<RD Value[iR, iC]> <NUL>
Next iC
Next iR

Example:
RSNUL0NULRRNUL3NULRCNUL4NULRNNULidNULiParam1NULfParam2NULsText1NULRDNUL
1NUL501NUL10.1NULText Example 1NUL
2NUL502NUL10.2NULText Example 2NUL
3NUL503NUL10.3NULText Example 3NUL

206/208
6.1.3 Error Codes Return-Value

Error Number Error Description

0 No error, request data to follow


1 Unknown SQL Command
2 Request returns more datasets than defined by MaxRows, modify request or increase MaxRows
3 Request returns more columns than defined by MaxColumns, modify request or increase MaxColumns
4 Request returns more data than defined by buffer size (only with target type Siemens)
Modify request or increase Buf. Size in the Connector and in the application.
5 Request returns minimal one value that is bigger than defined by MaxStringLength, modify request or increase
MaxStringLength
10 Internal Connector error
11 Internal Connector error, cannot open database
23 Request string is empty
24 Number MaxRows not defined
25 Number MaxColumns not defined
29 Size MaxStringLength not defined
>100 Error numbers of the ODBC database connection (some known error numbers are attached)
40002 General error during SQL request, request string is invalid

207/208
6.1.4 Handshake

Error-free Request

xExecute

xAbort

xReady

xBusy

xDone

xError

Abortion during Request

xExecute

xAbort

xReady

xBusy

xDone

xError

Error during Request

xExecute

xAbort

xReady

xBusy

xDone

xError

208/208

You might also like