簡體   English   中英

在Java語句中執行多個命令

[英]execute multiple commands in java statement

嘗試執行插入操作,然后獲取最后一個id值,但是我發現select語句失敗,但是當我將其放入mysql工作台時它可以正常工作。 什么是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) {}
}

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,但我不知道該如何處理。 為什么你不使用休眠之類的東西。 插入的實體將在交易結束后自動獲得其ID集。

是的,這是您的問題:

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

您的SELECT語句不是更新。 但是您要進行的JDBC調用是執行UPDATE。

將其分為兩個呼叫。 單獨執行SELECT

並且不要忘記關閉ResultSet對象(也許在finally塊中)。

這是我在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;} } } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM