Establish first connection to the database
Establish first connection to the database
Prerequisites
MySQL server is installed and running
You know the IP address of the server
You have a MySQL username and password
A database has already been created
Declare variables
VAR
// Connection parameters
sHost : STRING := '192.168.1.100'; // IP address of your MySQL server
uiPort : UINT := 3306; // Default MySQL port
sDatabase : STRING := 'testdb'; // Name of your database
sUsername : STRING := 'root'; // Your username
sPassword : STRING := 'MeinPasswort123'; // Your password
// Control
xDoOpen : BOOL := FALSE; // Trigger to open
xConnected : BOOL := FALSE; // Status: connected
// Function block
MySQL_ConnString : MySQL_ConnectionString; // Connection object
fbMySQL_Open : MySQL_Open; // Function block
// Error handling
eError : ERROR; // Error code
sExecuteState : STRING(200); // Status message
END_VAROpen connection - code
// Open connection when xDoOpen is TRUE
IF xDoOpen THEN
fbMySQL_Open(
sHost := '192.168.1.100', // CHANGE: your server IP
uiPort := 3306,
sDatabase := 'testdb', // CHANGE: your database name
sUsername := 'root', // CHANGE: your username
sPassword := 'MeinPasswort123', // CHANGE: your password
xStart := xDoOpen,
MySQL_Connection:= MySQL_ConnString,
xConnected => xConnected,
eError => eError,
sExeute_State => sExecuteState
);
END_IFImportant values to adjust
sHost
'192.168.1.100'
IP address of your server (for local server: '127.0.0.1' or 'localhost')
uiPort
3306
Default port, normally do not change
sDatabase
'testdb'
Name of your database in phpMyAdmin or MySQL Workbench
sUsername
'root'
MySQL username (default: 'root')
sPassword
'MeinPasswort123'
Password you set during MySQL installation
Troubleshooting
eError = 1
Server unreachable
Check IP address and network connection
eError = 2
Authentication failed
Check username and password
eError = 3
Timeout
Check firewall settings, port 3306 must be open
eError = 4
Database does not exist
Check database name, create database if necessary
Last updated

