java使用getGeneratedKeys()打印密钥不起作用。为什么?
为什么getGeneratedKeys()返回NULL?这是我的代码:
public void insertNewPreventivo(String cliente, int idProdottoNew, int[] opzioniNew) {
String query = "INSERT INTO preventivo (prodotto,cliente) VALUES (?,?)";
ResultSet rs = null;
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(query, ps.RETURN_GENERATED_KEYS);
ps.setInt(1, idProdottoNew);
ps.setString(2, cliente);
ps.executeUpdate();
rs = ps.getGeneratedKeys();
if (rs.next()) {
System.out.println(rs.getString(1));
}
}
catch (SQLException e) {
e.printStackTrace();
}
这是我的数据库:
+-----------+-------------+------+-----+-------------------+-------------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+-------------------+-------------------+
| id | datetime | NO | PRI | CURRENT_TIMESTAMP | DEFAULT_GENERATED |
| prodotto | int | NO | MUL | NULL | |
| cliente | varchar(45) | NO | MUL | NULL | |
| impiegato | varchar(45) | YES | MUL | NULL | |
| prezzo | double | NO | | 0 | |
+-----------+-------------+------+-----+-------------------+-------------------+
我要打印“id”值。谢谢
# 1 楼答案
executeUpdate
方法从不返回生成的密钥。给你行数改为使用
execute()
并使用getGeneratedKeys()获取结果集此外,“某些驱动程序”需要给出
generated
列名,而不是常量(返回生成的\u键)像这样
PreparedStatement ps = con.prepareStatement(sql, new String[]{"id"})