JDBC PreparedStatementの例 – レコードを削除する
次に、JDBC PreparedStatementを使用してテーブルからレコードを削除する方法を示す例を示します。 delete文を発行するには、次のように `PreparedStatement.executeUpdate()`メソッドを呼び出します。
String deleteSQL = "DELETE DBUSER WHERE USER__ID = ?"; PreparedStatement preparedStatement = dbConnection.prepareStatement(deleteSQL); preparedStatement.setInt(1, 1001);//execute delete 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 JDBCPreparedStatementSelectExample { 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 { deleteRecordFromTable(); } catch (SQLException e) { System.out.println(e.getMessage()); } } private static void deleteRecordFromTable() throws SQLException { Connection dbConnection = null; PreparedStatement preparedStatement = null; String deleteSQL = "DELETE DBUSER WHERE USER__ID = ?"; try { dbConnection = getDBConnection(); preparedStatement = dbConnection.prepareStatement(deleteSQL); preparedStatement.setInt(1, 1001); //execute delete SQL stetement preparedStatement.executeUpdate(); System.out.println("Record is deleted!"); } 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; } }