Python Forum

Full Version: Write to SQL Table
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How can I change my code to write to a SQL Table instead to a Excel File

The code I use is this one

from pylogix import PLC
import sys
sys.path.append('..')
import time
import pandas as pd

plc_data = pd.read_excel("Actuadores.xlsx", sheet_name='Result')
with PLC() as comm:
    comm.IPAddress = '172.21.12.10'
    comm.ProcessorSlot = 0
    ret = comm.GetPLCTime()
    print( "Fecha y Hora de Registro Revision Fallas", ret.Value)
    time.sleep(1)
    Estacion = "D2R_030"
    Estacion2 = "D2R_040"
    Estacion3 = "D2R_050"
    Estacion4 = "D2R_060"
    Estacion5 ="D2M_120"
    Estacion6 = "D2R_130"
    Estacion7 = "D2M_140"
#------------------------------------------------------------------------------------------ ESTACION D2R_030 -------------------------------------------------------------------------------#
    print("INICIO DE REVISION ESTACION :" , Estacion)
#ACTUADOR 1 
    ACTUADOR = comm.Read('D2R_030.Status.Act._1.WBypassed')
    ret = comm.GetPLCTime()
    Numero_Act_EnBypass = 0
    
    if ACTUADOR.Value == True:
        Sensor = "ACTUADOR 1 WORK SENSOR EN BY PASS"
        Numero_Act_EnBypass= (Numero_Act_EnBypass+1)
        temp_dict = {'PLC IP': comm.IPAddress, 'Date Time': ret.Value, 'Estacion': Estacion, 'Tag': ACTUADOR, 'Value': Sensor}
        plc_data = plc_data.append(temp_dict.copy(), ignore_index=True)
        plc_data.to_excel("Actuadores.xlsx", sheet_name='Result', index=False) 
        print(Sensor)

    else:
        Sensor = "ACTUADOR 1 WORK OK" 
        print(Sensor)
The values that I need in the table are
PLC IP
Date Time
Estacion
Tag
Value
you need to connect to a database instance, then do insert statements and commit them
It is pretty much the same across all DBMS's, but there are slight differences.
At any rate, there is an unavoidable learning curve (small) involved with with each DBMS.

A more generic approach would be to use SQLAlchemy, which uses dstabase models.
to change from one DBMS to another is usually a one line change.

I have an SQLAlchemy tutorial here: https://python-forum.io/Thread-SqlAlchem...SQLalchemy

It's worth the small amount of time needed to learn the basics, as sqlalchemy makes it all easy.