Marcio Cunha

How to Integrate a PLC to a Database: Architecture and Practical Code

Learn how to connect a Programmable Logic Controller to relational and time-series databases. Explore polling strategies, edge gateways, and industrial communication patterns to eliminate data bottlenecks on the factory floor.

Marcio Cunha4 min
Also available in:EspañolPortuguês
Summary
  • Direct connections between industrial controllers and relational databases require careful management due to the strict memory limits of hardware.
  • Using intermediate edge computers isolates automation networks from database downtime and improves overall system resilience.
  • Open protocols like MQTT and OPC UA enable structured transmission of process variables without rigid vendor lock-in.
  • Time-series databases outperform traditional relational storage engines when handling high-frequency industrial telemetry data.
  • Local buffering strategies ensure the preservation of critical telemetry during temporary network connectivity drops.

The Historical Disconnect Between the Factory Floor and Enterprise Systems

For decades, the factory floor and the executive suite spoke entirely different languages. On one side, the PLC (Programmable Logic Controller), a rugged computer designed to actuate motors and read sensors within milliseconds. On the other, the corporate database, guardian of financial spreadsheets and production reports. Integrating these two worlds used to require complex acrobatics involving proprietary software and expensive licenses. In practice, this meant that much of the analytical potential of industrial automation remained trapped inside closed memory cards, with no visibility for the rest of the enterprise.

Today, the demand for global efficiency requires data generated at the edge of an assembly line to reach management dashboards and predictive algorithms rapidly. However, connecting automation hardware directly to a relational database like PostgreSQL or MySQL is rarely the ideal path. PLCs operate in deterministic real-time, executing rigid read-and-write cycles, while database servers handle concurrency, transactions, and unpredictable latencies. Forcing a direct communication channel without a clear architectural strategy can freeze the controller due to memory exhaustion or crash the system from connection overloads.

Integration Topologies: Choosing Where Processing Occurs

The most critical decision when planning this integration is determining where the data translation intelligence resides. The traditional approach relied on proprietary libraries or OPC drivers directly inside the PLC ladder logic to write SQL rows. While functional for small systems, this practice consumes precious processing resources from the industrial hardware and creates rigid dependencies. If the database server needs a reboot for maintenance, the PLC may experience communication faults and halt the production process.

The modern and recommended alternative involves adopting an edge-based architecture using an intermediate industrial computer or IoT gateway. This lightweight device communicates with the PLC via native industrial protocols like Modbus TCP or Ethernet/IP, collects required variables, and pushes them asynchronously to the database. In practice, this separation of responsibilities shields the automation network from network instabilities, allowing the database to go offline for hours without stopping a single conveyor belt.

Communication Protocols and the Role of OPC UA

When moving data from the shop floor to IT systems, protocol selection defines project success. The dominant industrial standard for this purpose is OPC UA (Open Platform Communications Unified Architecture), a secure, cross-platform, structured protocol encapsulating automation tags with rich metadata. Unlike legacy protocols that transmit only raw numbers, OPC UA indicates whether the value read from a temperature sensor is of good, uncertain, or invalid quality.

For cloud-focused scenarios and event-driven architectures, the MQTT protocol stands out due to its lightweight footprint and publish-subscribe mechanism. The PLC or gateway publishes variable states only upon significant changes, saving network bandwidth and avoiding redundant storage of static data. Transitioning from traditional polling—where the system repeatedly asks 'what is the value now?'—to an event-driven model represents a dramatic leap in the plant's energy and computational efficiency.

Implementing Data Collection and Push with Python and Modbus

To illustrate the practical side of integration, we can build a simple Python script running on an edge gateway. This script periodically reads temperature registers from a PLC via Modbus TCP and inserts the values into a PostgreSQL database. In practice, this approach forms the foundation for lightweight monitoring systems where the complexity of full OPC UA servers is not yet justified.

import time
import psycopg2
from pymodbus.client import ModbusTcpClient

# Connection settings
PLC_IP = '192.168.1.50'
DB_CONFIG = {'dbname': 'factory', 'user': 'operator', 'password': '123', 'host': 'localhost'}

client = ModbusTcpClient(PLC_IP)
client.connect()

def collect_and_persist():
    # Reading holding register 30001 (Furnace temperature)
    result = client.read_holding_registers(0, 1)
    if not result.isError():
        temperature = result.registers[0] / 10.0
        
        connection = psycopg2.connect(**DB_CONFIG)
        cursor = connection.cursor()
        cursor.execute('INSERT INTO furnace_readings (temperature) VALUES (%s)', (temperature,))
        connection.commit()
        cursor.close()
        connection.close()
        print(f'Data saved successfully: {temperature} °C')

while True:
    try:
        collect_and_persist()
    except Exception as e:
        print(f'Integration error: {e}')
    time.sleep(5)

The code above demonstrates the conceptual simplicity of an edge data collector. However, in a real production environment, handling network failure scenarios is paramount. If the database connection drops, the script must store records locally in a file or lightweight database like SQLite to prevent permanent data loss during outages. This resilience separates academic prototypes from reliable industrial systems.

Choosing the Right Database: Relational versus Time-Series

Another frequent dilemma in industrial data engineering is selecting the ideal database. Traditional relational databases like PostgreSQL handle product catalog tables, manufacturing orders, and batch parameters seamlessly. However, when hundreds of sensors push readings every second, data volume grows exponentially, degrading time-query performance and disk space utilization.

To solve this bottleneck, modern engineers combine relational databases with time-series optimized engines like InfluxDB or TimescaleDB. These specialized technologies drastically compress sequential records based on timestamps, enabling instant queries across massive historical intervals. In practice, this segmentation ensures that the transactional structure of the factory is not suffocated by the ocean of raw data generated by process sensors.

Final Considerations on Security and Scalability

Integrating a PLC into a database transcends mere data transfer coding; it connects operational automation to corporate intelligence with rigorous cybersecurity. The use of segmented networks, industrial firewalls, and encryption in transit prevents office vulnerabilities from reaching the factory's physical control core. By planning this journey with edge gateways, open protocols, and proper databases, companies ensure real-time operational visibility without compromising machine stability and safety.