在java语句中执行多个命令

时间:2014-04-09 17:53:37

标签: java mysql

尝试执行插入然后获取最后一个id值,但是我得到select语句失败,但是当我把它扔进mysql workbench时它工作正常。什么是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) {}
}

3 个答案:

答案 0 :(得分:0)

exececuteUpdate永远不会返回ResultSet。参见:

int executeUpdate(String sql) throws SQLException

http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)

您必须查询新记录。 你可以尝试:getGeneratedKeys

但是很久以前我使用普通的java.sql我不知道我们是怎么回事。 为什么你不使用像hibernate这样的东西。插入的实体将在事务结束后自动获取其id。

答案 1 :(得分:0)

是的,这是你的问题:

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

您的SELECT声明不是更新。但是你正在进行的JDBC调用是进行更新。

将其拆分为两个电话。单独执行SELECT

不要忘记关闭ResultSet个对象(可能在finally块中)。

答案 2 :(得分:0)

以下是我在DAO中编写的一些代码,用于使用JDBC将带有wordID的单词添加到数据库表中,它说明了如何将一行添加到表中以获取生成的密钥。单词表中的第一列是INT(当数据库为null时由数据库自动生成),第二列是包含提供的单词的VARCHAR。 Word类(未显示)只是一个简单的类来封装wordID整数和一个带有getter和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;}
    }
}

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;} } }