iT邦幫忙

2024 iThome 鐵人賽

DAY 12
0
自我挑戰組

資料庫與Java開發工具連接系列 第 12

D12:撰寫程式碼控制資料庫-寫入、刪除(中)

  • 分享至 

  • xImage
  •  

昨天分享了如何利用程式碼寫入、刪除一筆資料,但是一次只能處理一筆資料太慢了,今天要分享如何一次處理多筆資料~~

要先定義資料

我們使用到的資料是儲存在二維陣列裡的,大概長這樣,是一個名為students的二維陣列,裡面存了很多項table所要求的(number, name, gender, age),每項資料以{}分開。

Object[][] students = {
            {111, "早安", "早不安", 11},
            {222, "午安", "午不安", 22},
            {333, "晚安", "晚不安", 33},
            {444, "半夜安", "半夜不安", 44},
            {555, "凌晨安", "凌晨不安",55},
        };

撰寫程式碼

我們的新Method叫做insertDatas,在呼叫時需要輸入一個二維陣列,就是上面定義的那個,在中間那段for-each迴圈是把我們所定義的二維陣列內的每筆資料(a,b,c,d)都設定成對應的資料類型(Integer、String)並依次代入每個(?, ?, ?, ?),最後的addBatch是把代入後的每筆資料添加進一個流程(?),在最後的executeBatch()執行完這個流程後,所有的資料就會寫入我們的資料庫啦!

public static void insertDatas(Object[][] students) {
        String insertSQL = "INSERT INTO student_information (number, name, gender, age) VALUES (?, ?, ?, ?)";

        try (Connection connection = DriverManager.getConnection(JDBC_url, JDBC_user, JDBC_password);
            PreparedStatement preparedStatement = connection.prepareStatement(insertSQL)) {

            for (Object[] student : students) {
                preparedStatement.setInt(1, (Integer) student[0]);
                preparedStatement.setString(2, (String) student[1]);
                preparedStatement.setString(3, (String) student[2]);
                preparedStatement.setInt(4, (Integer) student[3]);
                preparedStatement.addBatch();
            }

            int[] rowsAffected = preparedStatement.executeBatch();

            System.out.println("Batch insert successful! " + rowsAffected.length + " row(s) added.");


        } catch (SQLException e) {
            e.printStackTrace();
        }

https://ithelp.ithome.com.tw/upload/images/20240926/201694066U6YZn3O5Q.png


上一篇
D11:撰寫程式碼控制資料庫-寫入、刪除(上)
下一篇
D13:撰寫程式碼控制資料庫-寫入、刪除(下)
系列文
資料庫與Java開發工具連接26
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言