如何从插入中获取id和时间?

时间:2014-03-22 22:51:41

标签: java sql derby

我有这样的表

CREATE TABLE example
(
  id INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
  number DOUBLE NOT NULL,
  date DATE DEFAULT CURRENT DATE
);

我可以使用代码

取回id
Connection connection = null;
try {
  connection = DriverManager.getConnection("jdbc:derby://localhost:1527/database","root","root");
  connection.setAutoCommit(false);
  PreparedStatement query = connection.prepareStatement("INSERT INTO example (number) VALUES (?)", Statement.RETURN_GENERATED_KEYS);
  query.setInt(1, 12);
  query.executeUpdate();

  ResultSet rs = query.getGeneratedKeys();

  while (rs.next()) {
    System.out.println(rs.getInt(1));
    //System.out.println(rs.getDate(2));
  }

  connection.commit();
} catch (SQLException e) {
  if(connection != null){
    try {
      connection.rollback();
    } catch (SQLException e1) {
      Logger.getLogger("meh").log(Level.SEVERE, null, e1);
    }
  }
  Logger.getLogger("meh").log(Level.SEVERE, null, e);
}finally {
  try {
    if(connection != null)
      connection.close();
  } catch (SQLException e) {
    Logger.getLogger("meh").log(Level.SEVERE, null, e);
  }
}

但是当我试图取消注释第二个println时,出现错误:"列位置' 2'超出范围。此ResultSet的列数为' 1'。"。那么这里有什么方法可以回到那个时候吗?

0 个答案:

没有答案