2014-04-09 41 views
0

尝试执行插入操作,然后获取最后一个id值,但是我得到的结果是select语句失败,但它在我将它放入mysql工作台时工作正常。什么是Java代码失败?在java语句中执行多个命令

import java.sql.Connection 
import java.sql.DriverManager 
import java.sql.SQLException 
import java.sql.Statement 
import java.sql.ResultSet 
String url = "jdbc:mysql://localhost:3306/"; 
String user = "root" 
String password = "password" 
Connection connection = null; 
try { 
    System.out.println("Connecting database..."); 
    connection = DriverManager.getConnection(url,user,password); 
    Statement stmt = connection.createStatement(); 
    ResultSet rs = stmt.executeUpdate("INSERT INTO table_listnames (name) VALUES ('alex'); SELECT LAST_INSERT_ID() as lastId;"); 
    while (rs.next()) { 
     String lastId = rs.getString("lastId"); 
     println(lastId) 
    } 
    println("closing now") 
    stmt.close() 
    connection.close() 
} catch (SQLException e) { 
    throw new RuntimeException("Cannot connect the database!", e); 
} finally { 
    System.out.println("Closing the connection."); 
    if (connection != null) try { 
     connection.close(); 
    } catch (SQLException ignore) {} 
} 
+0

更大图片溶液:http://stackoverflow.com/questions/1915166/how-to-get-the-insert-id-in-jdbc –

回答

0

啊,这是你的问题:

ResultSet rs = stmt.executeUpdate("INSERT INTO table_listnames (name) VALUES ('alex'); SELECT LAST_INSERT_ID() as lastId;"); 

SELECT说法是不更新。但是您所做的JDBC调用是执行UPDATE。

将其拆分为两个调用。分开做SELECT

不要忘了关闭你的ResultSet对象(也许在finally块中)。

0

下面是我在DAO中编写的一段代码,它使用JDBC向数据库表中添加一个带wordID的单词,它说明了如何向表中添加一行以获取生成的密钥。单词表中的第一列是一个INT(当数据库为空时由数据库自动生成),第二列是包含提供的单词的VARCHAR。 Word类(没有显示)只是一个简单的类来封装wordID integer和一个带有getters和setter的String。

尽管它比你的问题稍微复杂一些,因为它也包含JNDI和准备好的语句,但这段代码应该让你开始。

/** Attempts to add a Word. Returning a clone of the word including the wordID on success */ static final Word createWord(final Word word) throws Exception {
InitialContext initialContext = null; DataSource ds = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null;

try{ 
     initialContext = new InitialContext(); 
     ds = (DataSource) initialContext.lookup("java:/comp/env/jdbc/MyDatabase"); 
     conn = ds.getConnection(); 
     if(word.getWordID() == 0) 
     { 
      stmt = conn.prepareStatement("INSERT INTO words VALUES(?,?)", Statement.RETURN_GENERATED_KEYS); 
      stmt.setNull(1, Types.INTEGER);   //wordID 
      stmt.setString(2, word.getText()); 

      // execute the insert and get the new wordID 
      int rowsAdded = stmt.executeUpdate();  
      if(rowsAdded == 0)return null;    
      Integer key = null; 
      rs = stmt.getGeneratedKeys(); 
      if(rs.next()){key = new Integer(rs.getInt("GENERATED_KEY"));} 
      rs.close(); 

      // clone the word but add in the word id 
      Word retval = new Word(word.getText()); 
      retval.setWordID(key); 
      return retval; 
     } 
     return null;  
    } 
    catch(NamingException e) 
    {   
     throw new Exception("WordDAO: failed to obtain DataSource", e); 
    } 
    catch (SQLException e) 
    { 
     e.printStackTrace(); 
     if(Log.isLogError())Log.error("WordDAO: SQLException" + e.getMessage(), e); 
     return null; 
    } 
    finally 
    { 
     // Always make sure result sets and statements are closed and the connection is returned to the pool 
     if (rs != null){try{rs.close();}catch (SQLException e){}rs = null;} 
     if (stmt != null){try{stmt.close();}catch(SQLException e){}stmt = null;} 
     if (conn != null){try {conn.close();}catch(SQLException e){}conn = null;} 
    } 
}