有 Java 编程相关的问题?

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

java从MySQL数据库获取插入行的索引

我正在使用Java(jdbc)与MySQL数据库交互。我有一个主索引是自动递增的表。当我插入一行时,我需要得到它刚刚收到的索引。我该怎么做


共 (3) 个答案

  1. # 1 楼答案

    发件人:http://dev.mysql.com/doc/refman/5.0/en/connector-j-usagenotes-basic.html#connector-j-usagenotes-last-insert-id

    stmt.executeUpdate(
            "INSERT INTO autoIncTutorial (dataField) "
            + "values ('Can I Get the Auto Increment Field?')",
            Statement.RETURN_GENERATED_KEYS);
    
    //
    // Example of using Statement.getGeneratedKeys()
    // to retrieve the value of an auto-increment
    // value
    //
    
    int autoIncKeyFromApi = -1;
    
    rs = stmt.getGeneratedKeys();
    
    if (rs.next()) {
        autoIncKeyFromApi = rs.getInt(1);
    } else {
    
        // throw an exception from here
    }
    
    rs.close();
    
    rs = null;
    
  2. # 2 楼答案

    或者,使用Spring JDBC,它看起来像:

     Map<String, Object> map = new HashMap<String, Object>();
     map.put("column1", "test");
     map.put("column2", Boolean.TRUE);
    
     SimpleJdbcInsert insert = new SimpleJdbcInsert(template).withTableName("table").usingGeneratedKeyColumns("id");
     int id = insert.executeAndReturnKey(map).intValue();
    
  3. # 3 楼答案

    感谢约翰·博克的出色回应

    如果希望使用PreparedStatement,仍然可以使用^{,但必须以不同的方式应用命令:

    PreparedStatement ps = mysql.prepareStatement(
        "INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)",
         Statement.RETURN_GENERATED_KEYS );
    ps.setString(1, "My text");
    ps.setTimestamp(2, new java.sql.Timestamp(new java.util.Date().getTime()););
    ps.setInt(3, 5150);
    ps.executeUpdate();
    ResultSet results = ps.getGeneratedKeys();
    results.next(); // Assume just one auto-generated key; otherwise, use a while loop here
    System.out.println(results.getInt(1)); // there should only be 1 column in your results: the value of the auto-generated key
    
    1. prepareStatement()中添加RETURN_GENERATED_KEYS参数 功能
    2. 不是从statement.executeUpdate()而是从 statement.getGeneratedKeys()