動力節點筆記java
- import java.sql.*;
- //採用Batch添加數據
- public class BatchTest01 {
- public static void main(String[] args) {
- Connection conn = null;
- PreparedStatement pstmt = null;
- try {
- //第一步,加載數據庫驅動,不一樣的數據庫驅動程序不同
- Class.forName("oracle.jdbc.driver.OracleDriver");
- //第二部,獲得數據庫鏈接
- String dburl = "jdbc:oracle:thin:@localhost:1521:orcl";
- //String dburl = "jdbc:oracle:thin:@192.168.21.1:1521:orcl";
- //String dburl = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
- String userName = "system";
- String password = "wanwan";
- conn = DriverManager.getConnection(dburl, userName, password);
- //System.out.println(conn);
- String sql = "insert into enp(empno, ename) values(?, ?)";
- pstmt = conn.prepareStatement(sql);
- for (int i = 0; i < 10; i++) {
- pstmt.setInt(1, 8000 + i);
- pstmt.setString(2, "趙" + i);
- //這種方式與數據庫打交道的次數比較頻繁
- //若是數據庫與應用程序再也不一臺機器上,那麼會有性能的損耗
- //因此跨網絡的傳輸最好粒度粗一點
- pstmt.executeUpdate();
- }
- System.out.println("添加員工成功");
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- //注意關閉原則:從裏到外
- try {
- if (pstmt != null) {
- pstmt.close();
- }
- if (conn != null) {
- conn.close();
- }
- } catch(SQLException e) {
- }
- }
- }
- }
- import java.sql.*;
- //採用Batch添加數據
- public class BatchTest02 {
- public static void main(String[] args) {
- Connection conn = null;
- PreparedStatement pstmt = null;
- try {
- //第一步,加載數據庫驅動,不一樣的數據庫驅動程序不同
- Class.forName("oracle.jdbc.driver.OracleDriver");
- //第二部,獲得數據庫鏈接
- String dburl = "jdbc:oracle:thin:@localhost:1521:orcl";
- //String dburl = "jdbc:oracle:thin:@192.168.21.1:1521:orcl";
- //String dburl = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
- String userName = "system";
- String password = "wanwan";
- conn = DriverManager.getConnection(dburl, userName, password);
- //System.out.println(conn);
- String sql = "insert into enp(empno, ename) values(?, ?)";
- pstmt = conn.prepareStatement(sql);
- for (int i = 1; i <= 100; i++) {
- pstmt.setInt(1, 9000 + i);
- pstmt.setString(2, "張_" + i);
- pstmt.addBatch();
- if (i % 10 == 0) {
- //批量更新
- pstmt.executeBatch();
- }
- }
- pstmt.executeUpdate();
- System.out.println("添加員工成功");
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- //注意關閉原則:從裏到外
- try {
- if (pstmt != null) {
- pstmt.close();
- }
- if (conn != null) {
- conn.close();
- }
- } catch(SQLException e) {
- }
- }
- }
- }