如何使用preparedStatement插入last_insert_id?

时间:2014-02-01 07:59:11

标签: java mysql

我在准备好的语句中插入“last_insert_id”时遇到了困难。我有如何在预备语句中选择last_insert_id,如下所示:

PreparedStatement getLastInsertId = con.prepareStatement("SELECT LAST_INSERT_ID()");

当我使用相同的过程在我的预备句中插入last_insert_id时:

1.  PreparedStatement pst =  con.prepareStatement("insert into introducer_table  values(?,?,?,?)");
2.     
3.     //introducer details into database
4.       pst.setString(1,LAST_INSERT_ID());
5.     pst.setString(2, nameofintroducer);
6.     pst.setString(3, accountno);
7.     pst.setString(4, signofintroducer);

我在第一栏中获得了'null'值。任何人都可以帮我解决这个问题

1 个答案:

答案 0 :(得分:1)

如果您同时使用getGeneratedKeys()执行两个保存操作,那么它几乎就是java。

我不是SQL大师,但在这里我找到了一种使用getGeneratedKeys()获取生成ID的方法

    long generatedId= 0L;
    statement = con
            .getConnection()
            .prepareStatement(
                    "insert into  new_user set name= ? , contact= ? , ....",
                    statement.RETURN_GENERATED_KEYS);
    statement.setString(1, "examplename");
    statement.setString(2, "examplecontact");
    ------
    statement.executeUpdate();
    ResultSet generatedKeys = statement.getGeneratedKeys();
    if (generatedKeys.next()) {
        generatedId = generatedKeys.getLong(1);// here is your generated Id , use it to  insert in your introducer_table
    }

     PreparedStatement pst =  con.prepareStatement("insert into introducer_table  values(?,?,?,?)");

         //introducer details into database
         pst.setString(1, generatedId);
         pst.setString(2, nameofintroducer);
         pst.setString(3, accountno);
         pst.setString(4, signofintroducer);