歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java實現批量插入、修改數據到數據庫中

Java實現批量插入、修改數據到數據庫中

日期:2017/3/1 9:06:08   编辑:Linux編程

在Java中使用JDBC實現批處理的對象一般是使用PrepareStatement對象。

如何使用:

Class.forName("Oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:demo" , "scott" , "tiger");
PreparedStatement ps = conn.prepareStatement("insert into dept2 values(? , ? , ?)");

for(Dept dept-> depts){
ps.setInt(1, dept.Id);
ps.setString(2, dept.Name);
ps.setString(3, dept.Description);
ps.addBatch();
}

ps.executeBatch();
ps.close();

conn.close();

同樣在批量更新時,也是使用這個PrepareStatement對象來處理的。

Class.forName("Oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:demo" , "scott" , "tiger");
PreparedStatement ps = conn.prepareStatement("update dept2 set name=? , description=? where id=?)");

for(Dept dept-> depts){
ps.setString(1, dept.Name);
ps.setString(2, dept.Description);
ps.setInt(3, dept.Id);
ps.addBatch();
}

ps.executeBatch();
ps.close();

conn.close();

Copyright © Linux教程網 All Rights Reserved