JDBC PreparedStatementの例 – レコードを更新する
次に、JDBC PreparedStatementを使用してテーブル内のレコードを更新する方法を示す例を示します。 update文を発行するには、次のように `PreparedStatement.executeUpdate()`メソッドを呼び出します。
String updateTableSQL = "UPDATE DBUSER SET USERNAME = ? WHERE USER__ID = ?"; PreparedStatement preparedStatement = dbConnection.prepareStatement(updateTableSQL); preparedStatement.setString(1, "mkyong__new__value"); preparedStatement.setInt(2, 1001);//execute insert SQL stetement preparedStatement .executeUpdate();
完全な例…
package com.mkyong.jdbc;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JDBCPreparedStatementUpdateExample {
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 {
updateRecordToTable();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
private static void updateRecordToTable() throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
String updateTableSQL = "UPDATE DBUSER SET USERNAME = ? "
+ " WHERE USER__ID = ?";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(updateTableSQL);
preparedStatement.setString(1, "mkyong__new__value");
preparedStatement.setInt(2, 1001);
//execute update SQL stetement
preparedStatement.executeUpdate();
System.out.println("Record is updated to DBUSER table!");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.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;
}
}