次に、JDBCステートメントを使用してテーブル内のレコードを更新する方法を示す例を示します。 update文を発行するには、次のように `Statement.executeUpdate()`メソッドを呼び出します。

Statement statement = dbConnection.createStatement();//execute the update SQL stetement
statement.executeUpdate(updateTableSQL);

完全な例…​

package com.mkyong.jdbc;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCStatementUpdateExample {

    private static final String DB__DRIVER = "oracle.jdbc.driver.OracleDriver";
    private static final String DB__CONNECTION = "jdbc:oracle:thin:@localhost:1521:MKYONG";
    private static final String DB__USER = "user";
    private static final String DB__PASSWORD = "password";

    public static void main(String[]argv) {

        try {

            updateRecordIntoDbUserTable();

        } catch (SQLException e) {

            System.out.println(e.getMessage());

        }

    }

    private static void updateRecordIntoDbUserTable() throws SQLException {

        Connection dbConnection = null;
        Statement statement = null;

        String updateTableSQL = "UPDATE DBUSER"
                + " SET USERNAME = 'mkyong__new' "
                + " WHERE USER__ID = 1";

        try {
            dbConnection = getDBConnection();
            statement = dbConnection.createStatement();

            System.out.println(updateTableSQL);

           //execute update SQL stetement
            statement.execute(updateTableSQL);

            System.out.println("Record is updated to DBUSER table!");

        } catch (SQLException e) {

            System.out.println(e.getMessage());

        } finally {

            if (statement != null) {
                statement.close();
            }

            if (dbConnection != null) {
                dbConnection.close();
            }

        }

    }

    private static Connection getDBConnection() {

        Connection dbConnection = null;

        try {

            Class.forName(DB__DRIVER);

        } catch (ClassNotFoundException e) {

            System.out.println(e.getMessage());

        }

        try {

            dbConnection = DriverManager.getConnection(
                              DB__CONNECTION, DB__USER,DB__PASSWORD);
            return dbConnection;

        } catch (SQLException e) {

            System.out.println(e.getMessage());

        }

        return dbConnection;

    }

}

結果

ユーザ名 “user

id = 1″は新しい値 ‘mkyong

new’に更新されます。

UPDATE DBUSER SET USERNAME = 'mkyong__new'  WHERE USER__ID = 1
Record is updated into DBUSER table!