简体   繁体   English

在Java语句中执行多个命令

[英]execute multiple commands in java statement

Trying to execute an insert then get the last id value but I get that the select statement fails, however it works when I throw it into mysql workbench it works fine. 尝试执行插入操作,然后获取最后一个id值,但是我发现select语句失败,但是当我将其放入mysql工作台时它可以正常工作。 What is the java code failing? 什么是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) {}
}

An exececuteUpdate whill never return a ResultSet. exececuteUpdate绝不会返回ResultSet。 See: 看到:

int executeUpdate(String sql) throws SQLException

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

You have to query for your new record. 您必须查询您的新记录。 You can try: getGeneratedKeys 您可以尝试:getGeneratedKeys

But it's so long time ago I used plain java.sql i doesn't know how we handelt that. 但是很久以前,我使用普通的java.sql,但我不知道该如何处理。 Why u doesn't use something like hibernate. 为什么你不使用休眠之类的东西。 An inserted entity wil automaticly get his id set after transaction end. 插入的实体将在交易结束后自动获得其ID集。

Yeah, this is your problem: 是的,这是您的问题:

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

Your SELECT statement isn't an update. 您的SELECT语句不是更新。 But the JDBC call you're making is to do an UPDATE. 但是您要进行的JDBC调用是执行UPDATE。

Split it into two calls. 将其分为两个呼叫。 Do the SELECT separately. 单独执行SELECT

And don't forget to close your ResultSet objects (perhaps in the finally block). 并且不要忘记关闭ResultSet对象(也许在finally块中)。

Here is some code I wrote in a DAO to add a word with a wordID into a database table using JDBC it illustrates how to add a row into a table get the generated key. 这是我在DAO中编写的一些代码,该代码使用JDBC将带有wordID的单词添加到数据库表中,它说明了如何向表中添加行以获取生成的键。 The first column in the word table is an INT (which gets autogenerated by the database when null), the second column is a VARCHAR containing the supplied word. 单词表中的第一列是INT(在为null时由数据库自动生成),第二列是包含所提供单词的VARCHAR。 The Word class (not shown) is just a trivial class to encapsulate the wordID integer and a String with getters and setters. Word类(未显示)只是一个琐碎的类,用于封装wordID整数和带有getter和setter的String。

Although it is a little more complex than your question as it contains JNDI and prepared statements as well, this code should get you started. 尽管它还包含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;} } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM