Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Write to SQL Table
#1
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
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  write json into a table herobpv 4 1,424 Jan-22-2023, 04:36 AM
Last Post: herobpv
  write mariadb table rows query to each file? shams 1 1,842 Feb-02-2021, 04:10 PM
Last Post: buran
  write csv data into teradata table sandy 0 5,085 Feb-13-2019, 12:11 AM
Last Post: sandy
  Write to db Table VodkaSodaWater 1 3,545 Aug-12-2017, 09:38 AM
Last Post: hbknjr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020