有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    executeUpdate方法从不返回生成的密钥。给你行数

    改为使用execute()并使用getGeneratedKeys()获取结果集

    此外,“某些驱动程序”需要给出generated列名,而不是常量(返回生成的\u键)

    像这样PreparedStatement ps = con.prepareStatement(sql, new String[]{"id"})