【发布时间】:2018-10-15 14:30:30
【问题描述】:
所以我尝试使用文件中的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)
所以问题
【问题讨论】:
-
你用的是什么关系型数据库?
-
这可能不是您的问题的根源,但在这种情况下,为变量名使用保留关键字来命名您的序列序列并不是一个好主意。
-
@StephaneM 我只是把它放在这里更容易理解
-
@Andrew 我正在使用 hsqldb
-
对于H2,我认为语法是
NEXTVAL('SequenceName')。
标签: java sql insert sequence h2