0

我正在开发一个连接到 Oracle 11g 数据库的应用程序,使用 ojdbc6 作为 JDBC 驱动程序。我为需要添加值的表创建了触发器和序列,以便该表的 ID 列自动递增。当我使用 SQL Developper 在数据库中手动添加新行时,一切正常(我的自动增量序列和触发器运行良好)。但是当涉及到从我的 Java 应用程序中添加新行时,我收到以下错误:

java.sql.SQLRecoverableException:在 oracle.jdbc.driver.OraclePreparedStatement.processCompletedBindRow(或 aclePreparedStatement.java:2247)在 oracle.jdbc.driver 的 oracle.jdbc.driver.OraclePreparedStatement.setupBindBuffers(OraclePreparedStatement.java:3071)的内部错误.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3444) 在 oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePrepar edStatement.java:3530) 在 oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(Oracl ePreparedStatementWrapper.java:1350)

这是我的 Java 代码:

String query = "INSERT INTO USER (ID, USERNAME, PASSWORD, FIRSTNAME, LASTNAME, EMAIL) VALUES (?, ?, ?, ?, ?, ?)";
        PreparedStatement preparedStatement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
        preparedStatement.setString(2, user.getUsername());
        preparedStatement.setString(3, user.getPassword());
        preparedStatement.setString(4, user.getFirstName());
        preparedStatement.setString(5, user.getFirstName());
        preparedStatement.setString(6, user.getEmail());

        preparedStatement.executeUpdate();

我没有为我的序列和触发器添加代码,因为我认为问题不是来自数据库,因为一切都适用于 sqldevelopper。我还尝试直接使用我的序列,例如:

String query = "INSERT INTO USER (ID, USERNAME, PASSWORD, FIRSTNAME, LASTNAME, EMAIL) VALUES (SEQUENCE.NEXTVAL, ?, ?, ?, ?, ?)";

但这也失败了

有人可以帮我解决这个问题吗?

4

3 回答 3

2

不要ID从客户端发送,让触发器处理ID

String query = "INSERT INTO USER (USERNAME, PASSWORD, FIRSTNAME, LASTNAME, EMAIL)"
  + " VALUES (?, ?, ?, ?, ?)";

PreparedStatement preparedStatement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, user.getUsername());
preparedStatement.setString(2, user.getPassword());
preparedStatement.setString(3, user.getFirstName());
preparedStatement.setString(4, user.getFirstName());
preparedStatement.setString(5, user.getEmail());

preparedStatement.executeUpdate();
于 2013-08-17T03:11:54.843 回答
1

在查询中为此提供一些默认值

    String query = "INSERT INTO USER (ID, USERNAME, PASSWORD, FIRSTNAME, LASTNAME, EMAIL) VALUES (?, ?, ?, ?, ?, ?)";
    PreparedStatement preparedStatement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
    preparedStatement.setInt(1, 0); // Providing default value as 0
    preparedStatement.setString(2, user.getUsername());
    preparedStatement.setString(3, user.getPassword());
    preparedStatement.setString(4, user.getFirstName());
    preparedStatement.setString(5, user.getFirstName());
    preparedStatement.setString(6, user.getEmail());

    preparedStatement.executeUpdate();
于 2013-08-17T03:48:39.513 回答
0
String query = "INSERT INTO USER (ID, USERNAME, PASSWORD, FIRSTNAME, LASTNAME, EMAIL) VALUES (0, ?, ?, ?, ?, ?)";

您的自动增量触发器会将 0 更新为序列中的下一个值。

于 2013-08-17T01:15:48.623 回答