Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6161533
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T21:29:49+00:00 2026-05-23T21:29:49+00:00

How can I execute the following query and retrieve a result via prepared statement:

  • 0

How can I execute the following query and retrieve a result via prepared statement:

INSERT INTO vcVisitors (sid) VALUES (?); SELECT LAST_INSERT_ID();

Is there a way to execute both two statements at once?

I’ve tried to do the following:

Connection con = DbManager.getConnection();
PreparedStatement ps = con.PrepareStatement(
     "INSERT INTO vcVisitors (sid) VALUES (?); SELECT LAST_INSERT_ID();");
ps.setInt(1, 10);
ResultSet rs = ps.exequteQuery();
rs.next();
return rs.getInt("LAST_INSERT_ID()");

but it gives me an error that executeQuery can’t execute such a query,
I’ve also tried to replace executeQuery by the following:

ps.execute();
rs = ps.getResultSet();

but it gives me SQL syntax error:

You have an error in your SQL syntax; 
check the manual that corresponds to your MySQL server version 
for the right syntax to use near 'SELECT LAST_INSERT_ID()' at line 1

but there are no problems with executing query
“INSERT INTO vcVisitors (sid) VALUES (’10’); SELECT LAST_INSERT_ID();”
directly from mysql console.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T21:29:51+00:00Added an answer on May 23, 2026 at 9:29 pm

    While updating (inserting) data use executeUpdate instead of executeQuery. Try executing SELECT LAST_INSERT_ID() as another query.

    But it is not portable query. I suggest using Statement.getGeneratedKeys instead. Please look here: JDBC (MySQL) Retrieving AUTO_INCREMENT Column Values.

    Here is an example of properly used LAST_INSERT_ID():

        Statement stmt = null;
       ResultSet rs = null;
    
       try {
    
        //
        // Create a Statement instance that we can use for
        // 'normal' result sets.
    
        stmt = conn.createStatement();
    
        //
        // Issue the DDL queries for the table for this example
        //
    
        stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial");
        stmt.executeUpdate(
                "CREATE TABLE autoIncTutorial ("
                + "priKey INT NOT NULL AUTO_INCREMENT, "
                + "dataField VARCHAR(64), PRIMARY KEY (priKey))");
    
        //
        // Insert one row that will generate an AUTO INCREMENT
        // key in the 'priKey' field
        //
    
        stmt.executeUpdate(
                "INSERT INTO autoIncTutorial (dataField) "
                + "values ('Can I Get the Auto Increment Field?')");
    
        //
        // Use the MySQL LAST_INSERT_ID()
        // function to do the same thing as getGeneratedKeys()
        //
    
        int autoIncKeyFromFunc = -1;
        rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");
    
        if (rs.next()) {
            autoIncKeyFromFunc = rs.getInt(1);
        } else {
            // throw an exception from here
        }
    
        rs.close();
    
        System.out.println("Key returned from " +
                           "'SELECT LAST_INSERT_ID()': " +
                           autoIncKeyFromFunc);
    
    } finally {
    
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ex) {
                // ignore
            }
        }
    
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ex) {
                // ignore
            }
        }
    }
    

    and here the same with getGeneratedKeys:

         Statement stmt = null;
       ResultSet rs = null;
    
       try {
    
        //
        // Create a Statement instance that we can use for
        // 'normal' result sets assuming you have a
        // Connection 'conn' to a MySQL database already
        // available
    
        stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
                                    java.sql.ResultSet.CONCUR_UPDATABLE);
    
        //
        // Issue the DDL queries for the table for this example
        //
    
        stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial");
        stmt.executeUpdate(
                "CREATE TABLE autoIncTutorial ("
                + "priKey INT NOT NULL AUTO_INCREMENT, "
                + "dataField VARCHAR(64), PRIMARY KEY (priKey))");
    
        //
        // Insert one row that will generate an AUTO INCREMENT
        // key in the 'priKey' field
        //
    
        stmt.executeUpdate(
                "INSERT INTO autoIncTutorial (dataField) "
                + "values ('Can I Get the Auto Increment Field?')",
                Statement.RETURN_GENERATED_KEYS);
    
        //
        // Example of using Statement.getGeneratedKeys()
        // to retrieve the value of an auto-increment
        // value
        //
    
        int autoIncKeyFromApi = -1;
    
        rs = stmt.getGeneratedKeys();
    
        if (rs.next()) {
            autoIncKeyFromApi = rs.getInt(1);
        } else {
    
            // throw an exception from here
        }
    
        rs.close();
    
        rs = null;
    
        System.out.println("Key returned from getGeneratedKeys():"
            + autoIncKeyFromApi);
    } finally {
    
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ex) {
                // ignore
            }
        }
    
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ex) {
                // ignore
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to execute the following query SELECT a.userid, COUNT(a.id) AS count_answers, SUM(v.yes_vote)
How can I execute the following query using Castle ActiveRecords and LINQ or HQL?
I wish to execute the following query on my application's SQliteDatabase. String sql =
The following query uses join operation, i want the same query to execute without
hi how can i include NSString in the following query.House is as NSString.If i
How can i perform an LIKE query within Linq? I have the following query
I have the following sql statement: SELECT COUNT(table2.programName), table2.programName FROM table1 LEFT JOIN table2
I'm trying to execute the following query through classic asp recordset - SQL =
My original question When I execute the following query in SQLite, I get this
How can you check to see if a user can execute a stored procedure

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.