Для обновления записей будем использовать метод 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 driverName = "org.apache.derby.jdbc.EmbeddedDriver"; private static final String connectionString = "jdbc:derby:derbyDB;create=true"; private static final String query = "UPDATE USERS_TABLE " + "SET USER_NAME = 'APetrov' " + "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 updated 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(driverName); Connection connection = DriverManager.getConnection(connectionString); return connection; } public static void main(String[] args) { StatementsExample app = new StatementsExample(); try { app.run(); } catch (SQLException e) { e.printStackTrace(); } } }
В результате в консоль будет выведено:
Record updated 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>