for i in range(len(meters)): sql = ("INSERT INTO meter (meter, power, energy, date_of_reading) VALUES (%s, %s, %s, %s)", (meters[i], power_calculation[i], energy_calculation[i], date_of_reading)) mycursor.execute(*sql)This will insert just the values for the last meter. You either move the
execute
inside the loop, or look at changing your code to using executemany
Something like this (code not tested):
import mysql.connector from pymodbus.client import ModbusTcpClient from datetime import datetime M01 = '192.168.30.156' #LOCATION 1 M02 = '192.168.22.95' #LOCATION 2 ips = [M01, M02] date_of_reading = datetime.now() meters = [ModbusTcpClient(ip) for ip in ips] readings = [] for meter in meters: power_register = meter.read_holding_registers(23322, 2) energy_register = meter.read_holding_registers(20480, 4) power_calculation = round((power_register.registers[0] * pow(2, 16) + power_register.registers[1]) * 0.01 / 1000, 2) energy_calculation = round((energy_register.registers[2] * pow(2, 16) + energy_register.registers[3]) * 0.01, 2) reading = meter, power_calculation, energy_calculation, date_of_reading readings.append(reading) sql = "INSERT INTO meter (meter, power, energy, date_of_reading) VALUES (%s, %s, %s, %s)" mydb = mysql.connector.connect( host="192.168.25.2", user="xxxx", password="xxxx", database="energetics" ) mycursor = mydb.cursor() mycursor.executemany(sql, readings) mydb.commit() mycursor.close() print("Success !")From here you can improve the code - using e.g. named tuple for readings, make your code use functions and/or OOP, etc.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs