Creation of a prepared statement inside a loop

早过忘川 提交于 2019-12-05 10:55:12
Geoffrey Wiseman

Some drivers do cache prepared statements, yes. For example, skim this Oracle documentation: http://docs.oracle.com/cd/B10501_01/java.920/a96654/stmtcach.htm

I don't believe there's anything that requires this to be true for all drivers, although certainly it seems like a likely feature of many JDBC drivers. It sounds like MySQL might not do this: How to use MySQL prepared statement caching?

That said, if you really want to use prepared statements efficiently, it seems like hanging on to an instance of a prepared statement that you use on each loop iteration makes a lot more sense.

1. If you are using the same PreparedStatement throughout the loop, then its better you keep the PreparedStatement outside the loop.

2. If you have sql statment which keeps changing inside the loop, then only its worth using it in the loop.

3. Moreover if its keep changing, then just use Statement instead of PreparedStatement, else the very purpose of PreparedStatement is lost as you keep changing it.

Also try disable autocommit with Connection.setAutoCommit(false) and that you use PreparedStatement.executeBatch()

Two ways so far i know.

1st Way

Its insert record one by one

final String sql = "INSERT INTO tablename(columnname) Values(?)";

PreparedStatement statement = connection.prepareStatement(sql);

while (condition) {
statement.setString(1,value);
statement.executeUpdate();
}

(or)

2nd way

It inserts all record as bulk insert

final String sql = "INSERT INTO tablename(columnname) Values(?)";

PreparedStatement statement = connection.prepareStatement(sql);

while (condition) {
statement.setString(1,value);
statement.addBatch();
}

statement.executeBatch();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!