Click here to Skip to main content
16,020,186 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear Community a pleasure to greet you, I am reading several HoldinRegister type registers for that I am using easymodbus in total will be 150 registers that must be read and saved each time a Coil type register changes from 0 to 1, the reading of these registers is done as follows:

Java
public static void main(String[] args) throws Exception
{
    ModbusClient modbusClient = new ModbusClient();
    modbusClient.Connect("127.0.0.1", 502);
    int[] inputRegisters = modbusClient.ReadHoldingRegisters(0, 149);
    for (int i=0; i < inputRegisters.length; i++)
        System.out.println("Holding Register  #"+i+": "+inputRegisters[i]);
}


The values of the registers are updated only when the Coil changes its value, then save those registers in the database, I think this is better because if they would be updating all the time it would consume too many resources.

My question now is how can I do to save that amount of data at the same time, searching the net I found an example using FOR but I don't understand very well how to integrate it since I can't make it work.

Java
String SQL = "INSERT INTO ingredients(date,regnumb,regval)"
    + "values (?,?,?)";

    mensaje="data inserted correctly";
    try{
        PreparedStatement sqls = (PreparedStatement) conn.prepareStatement(SQL);
       
        int rows =4;
     
             
        for(int i = 0; i
        sqls.setString(1, date);
        sqls.setString(2, regnumb);          
        sqls.setString(5, regval);
        sqls.addBatch();
} sqls.executeBatch();


thank you very much for your attention

What I have tried:

insert several records simultaneously with java and mysql
Posted
Updated 1-Apr-22 22:37pm

1 solution

You are setting SQL parameter 1, 2, and 5 (why 5 and not 3?) to the same values each time. You need something like:
Java
for (int i=0; i < inputRegisters.length; i++) {
    sqls.setString(1, date);
    sqls.setString(2, inputRegisters[i].number); // however you get the number      
    sqls.setString(3, inputRegisters[i].value);  // and the value
    sqls.addBatch();
}
int[] results = sqls.executeBatch();
//

See also Statement (Java Platform SE 7 )[^] and java.sql.PreparedStatement.addBatch java code examples | Tabnine[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900