Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PreparedStatement for several statements

Is it possible to use PreparedStatement for several statements?

E.g., I mean if String sql = "INSERT INTO OR INGNORE ... ; UPDATE ... ; INSERT INTO ..."; this

PreparedStatement pre = conn.prepareStatement(sql);
//...
pre.executeUpdate();

executes only first statement "INSERT INTO OR INGNORE ... (until semicolon). Is it possible to execute all at once?

like image 209
Vyacheslav Avatar asked Dec 20 '25 15:12

Vyacheslav


2 Answers

Is it possible to execute all at once?

this might depend on the implementation of the JDBC driver by the database vendor but in general I would not expect that to work.

like image 61
Timothy Truckle Avatar answered Dec 23 '25 05:12

Timothy Truckle


String[] query = { "insert into Gericht (classification,date,name,preisExtern,preisIntern) values (?,?,?,?,?)",
            "test" };
    PreparedStatement stmt;
    for (String str : query) {
        stmt = c.prepareStatement(str);
        stmt.addBatch();
    }
    stmt.executeBatch();

here is an example on how to use batch. if its not what you want, please tell me so.

as wished:

@XtremeBaumer how about when the parameters in prepared statement change? how can you change it dynamically?

Answer:

you can't. if you want several different queries to be executed at once, you can only use fixed statement, otherwise your code will be very large, and then you can do it manually by setting the parameters and adding it to a batch. batches are good if you have 1 query that gets different parameters and you want to add all at once

like image 42
XtremeBaumer Avatar answered Dec 23 '25 05:12

XtremeBaumer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!