Для удаление записей будем использовать метод Statement.executeUpdate(sql). Минимально необходимый код приведен ниже:
Connection connection = getConnection(); Statement statement = connection.createStatement(); statement.executeUpdate(query);
Полный код примера:
package statements; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class StatementsExample { private static final String DRIVER_NAME = "org.apache.derby.jdbc.EmbeddedDriver"; private static final String CONNECTION_STRING = "jdbc:derby:derbyDB;create=true"; private static final String QUERY = "DELETE FROM USERS_TABLE " + "WHERE ID = 1"; private void run() throws SQLException { Connection connection = null; Statement statement = null; try { connection = getConnection(); statement = connection.createStatement(); statement.executeUpdate(QUERY); System.out.println("Record deleted successfully"); } catch (Exception e) { e.printStackTrace(); } finally { if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } } private Connection getConnection() throws ClassNotFoundException, SQLException { Class.forName(DRIVER_NAME); Connection connection = DriverManager.getConnection(CONNECTION_STRING); return connection; } public static void main(String[] args) { StatementsExample app = new StatementsExample(); try { app.run(); } catch (SQLException e) { e.printStackTrace(); } } }
В результате в консоль будет выведено:
Record deleted successfully
Зависимости можно получить через Maven, pom.xml приведен ниже:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>ru.mydesignstudio</groupId> <artifactId>statements</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.apache.derby</groupId> <artifactId>derby</artifactId> <version>10.12.1.1</version> </dependency> </dependencies> </project>