Получение последовательности из SQL INSERT с JDBC - PullRequest
0 голосов
/ 15 октября 2018

Поэтому я пытаюсь добавить в базу данных, используя JDBC из файлов.И теперь, когда INSERTING мне нужно получить ID перед вставкой, было бы лучше, если бы база данных все еще использовала sequence.

В папке resources У меня есть файл с именем insert_plant.sql, который содержит этот запрос:

INSERT INTO PLANTS (id, plantname, species)
  VALUES (NEXT VALUE FOR sequence, ?, null);

И таблица сгенерирована с этим:

DROP SCHEMA public CASCADE;

CREATE SEQUENCE sequence START WITH 1;

CREATE TABLE PLANTS (
   id BIGINT NOT NULL PRIMARY KEY,
   plantname VARCHAR(255) NOT NULL,
   species VARCHAR(255) NULL,
);

И теперь в Java я называю это:

public static void insertIntoOrderTable(BasicDataSource basicDataSource, String plantname) throws  SQLException{
    Connection conn = null;
    PreparedStatement stmt = null;

    try {
        conn = basicDataSource.getConnection();
        stmt = conn.prepareStatement(Util.readFileFromClasspath("insert_plant.sql"));
        stmt.setString(1, plantname);
        stmt.executeUpdate();

        //Below is the line 57 (in error)
        ResultSet rs = stmt.executeQuery("SELECT sequence.NEXTVAL FROM PLANTS");
        if(rs.next()){
            System.out.println("ID" + rs.getInt(1));
        }

    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (stmt != null) {
            stmt.close();
        }
        if (conn != null) {
            conn.close();
        }
    }
}

И ошибка, которую я получаю:

java.sql.SQLFeatureNotSupportedException: feature not supported
at org.hsqldb.jdbc.JDBCUtil.notSupported(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.executeQuery(Unknown Source)
at org.apache.commons.dbcp.DelegatingStatement.executeQuery(DelegatingStatement.java:208)
at org.apache.commons.dbcp.DelegatingStatement.executeQuery(DelegatingStatement.java:208)
at database.PlantDao.insertIntoOrderTable(PlantDao.java:57)
at database.PlantDao.main(PlantDao.java:19)

Итак, вопрос

1 Ответ

0 голосов
/ 15 октября 2018

Как уже прокомментировал «The Impaler», нет необходимости выполнять второй оператор, с JDBC вы можете использовать

PreparedStatement stmt = conn.prepareStatement(sql, new String[]{"id"});

И получить значение из него:

ResultSet rs = stmt.getGeneratedKeys();
if(rs.next()){
    System.out.println(rs.getLong(1));
}

Итак, ваш метод будет выглядеть примерно так:

public static void insertIntoOrderTable(BasicDataSource basicDataSource, String plantname) throws  SQLException{
    Connection conn = null;
    PreparedStatement stmt = null;

    try {
        conn = basicDataSource.getConnection();
        stmt = conn.prepareStatement(Util.readFileFromClasspath("insert_plant.sql"), new String[]{"id"});
        stmt.setString(1, plantname);
        stmt.executeUpdate();

        ResultSet rs = stmt.getGeneratedKeys();
        if(rs.next()){
            System.out.println(rs.getLong(1));
        }

    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (stmt != null) {
            stmt.close();
        }
        if (conn != null) {
            conn.close();
        }
    }
}
...