如何在MySql中使用LAST_INSERT_ID()等效于@@ IDENTITY

时间:2015-08-12 07:49:09

标签: java mysql jdbc

在MySql中,我想使用等效的SQL @@ IDENTITY,我发现了这个LAST_INSERT_ID()。我在搜索中发现,即使存在不同的会话,它也会起作用。我想在当前会话中找到最后一个ID。我正在使用以下代码。

public static void main(String[] args) {

    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = null;
        conn = DriverManager.getConnection("jdbc:mysql://localhost/fuel","root", "");
        System.out.print("Database is connected !\n");

        Statement st = conn.createStatement();
        String response = "<food>";
        String insertQuery = "INSERT INTO transactions(user_input,fuel_response,execution_time)"+
                             "VALUES(?,?,?)";
        PreparedStatement prepareStatementObj = conn.prepareStatement(insertQuery);         
        prepareStatementObj.setString(1, "I drank a babyfood juice apple.");
        prepareStatementObj.setString(2, response);
        prepareStatementObj.setInt(3, 4500);            

        prepareStatementObj.execute();

        String queryForId = "SELECT LAST_INSERT_ID() FROM transactions";
        ResultSet rs2 = st.executeQuery(queryForId);
        if (!rs2.isBeforeFirst() ) {    
             System.out.println("No data"); 
        } else {
            while ( rs2.next() ) {
                int id = rs2.getInt("id");          
                System.out.println("Last id of this session was..."+id);
            }
        }

        conn.close();
    } catch(Exception e) {
        System.out.print("Do not connect to DB - Error:"+e);
    }
}

代码适用于插入,但我没有获得最后插入的ID。它给出了以下例外。
专栏&#39; id&#39;没找到。 如果你能提供帮助,我将感谢你。

3 个答案:

答案 0 :(得分:2)

修改您的选择以使用别名作为ID: -

SELECT LAST_INSERT_ID() as id FROM transactions

答案 1 :(得分:1)

您正试图抓住一个名为id的专栏,但是没有这样的专栏。当您获取最后插入的ID时,会得到一个名为last_insert_id()的列:

MySQL> select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
|                0 |
+------------------+
1 row in set (0.02 sec)

更容易通过索引获取它(使用.getInt(int))。这非常安全,因为您知道只返回一列。

答案 2 :(得分:1)

您可以使用以下代码获取最后一次插入ID。

 var clsStopwatch = function() {
   // Private vars
   var startAt = 0; // Time of last start / resume. (0 if not running)
   var lapTime = 0; // Time on the clock when last stopped in milliseconds

   var now = function() {
     return (new Date()).getTime();
   };

   // Public methods
   // Start or resume
   this.start = function() {
     startAt = startAt ? startAt : now();
   };

   // Stop or pause
   this.stop = function() {
     // If running, update elapsed time otherwise keep it
     lapTime = startAt ? lapTime + now() - startAt : lapTime;
     startAt = 0; // Paused
   };

   // Reset
   this.reset = function() {
     lapTime = startAt = 0;
   };

   // Duration
   this.time = function() {
     return lapTime + (startAt ? now() - startAt : 0);
   };
 };

 var x = new clsStopwatch();
 var $time;
 var clocktimer;
 var ourTime = 3;

 function pad(num, size) {
   var s = "0000" + num;
   return s.substr(s.length - size);
 }

 function formatTime(time) {
   var h = m = s = ms = 0;
   var newTime = '';

   h = Math.floor(time / (60 * 60 * 1000));
   time = time % (60 * 60 * 1000);
   m = Math.floor(time / (60 * 1000));
   time = time % (60 * 1000);
   s = Math.floor(time / 1000);
   ms = time % 1000;

   newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 3);
   return newTime;
 }

 function update() {
   $time.innerHTML = formatTime(x.time());
 }

 function start() {
   //Declare $time here, so update() knows which field it needs to update
   $time = document.getElementById('time');
   clocktimer = setInterval("update()", 41);
   x.start();
 }

 function stop() {
   x.stop();
   clearInterval(clocktimer);
 }

 function reset() {
   stop();
   x.reset();
   update();
 }