tags:

views:

113

answers:

3

Hi all,

I have the sample code.

public void UpdateTable1() {
    for (int t = 0; t < 20; t++) {

        if (consumer == 1 && number == 1 && provider1 == 31 && feedback == 1) {
            try {
                Class.forName(driverName);
                con = DriverManager.getConnection(url + dbName, "root", "mysql");
                try {
                    Statement st = con.createStatement();
                    int val = st.executeUpdate("INSERT Consumer1 VALUES ("
                        + 31 + "," + "'Printer'" + ", " + 1 + " " + ")");
                    System.out.println("1 row affected");
                } catch (SQLException s) {
                    System.out.println("SQL statement is not executed!");
                }
                con.close();
            }
        }
    }
}

I want to insert the same set of values(31,printer,1) into the table consumer2,consumer3.Is it possible without using another try catch statements...Please help me.

A: 

You could replace

"INSERT Consumer1 VALUES ("

with

"INSERT INTO Consumer" + (t + 1) + " VALUES ("
trashgod
+1  A: 

I hope I'm not offending, but are you sure you fully understand how try-catch works?

The reason that the try catch statement is inside the for for t loop, is (likely) that someone wanted to ensure that one failure will not prevent other iterations of the loop from taking place. You could end up with corrupted data that way.

The decision you have to make is whether you want to do all three insertions under the same try-catch or not.

To easily do three insertions, do a loop on i from 1 to 3, and every time create a different statement, by adding strings, so that the first time the table is Consumer1, the second time it is Consumer2, etc. Put the whole loop inside the try catch, or put the-try-catch inside the body of the loop.

Uri
A: 
Lars Andren