0

This is a java inserting values to database problem.

I want to insert data into my database but I get an exception that states "Query does not return results". What am I doing wrong? What should I return?

This is my function code:

public void commitToDB(String fName) throws SQLException {
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    String query = "INSERT INTO users (firstname)" + " VALUES (?)";
    try {
        preparedStatement = connection.prepareStatement(query);
        preparedStatement.setString(1, fName);

        // execute the preparedstatement
        resultSet = preparedStatement.executeQuery();
    }
    catch(Exception e) {
        System.out.println("Got an exception");
        System.out.println(e.getMessage());           
    }
    finally {
        preparedStatement.close();
        resultSet.close();
    }
}   
1
  • resultset is only needed if you have a select query. if its update/insert etc, you dont have to assign it to a resultset. what can come back from the method is an int if i remember correctly. this int only shows if it was successful or not Commented Apr 4, 2017 at 12:26

2 Answers 2

2

You wan to execute an update statement (Something that doesn't return a ResultSet) but you are trying to execute it as a query. I made this mistake too when I was working with a database driver in Java for the first time.

What you want to do is change:

resultSet = preparedStatement.executeQuery();

to this:

preparedStatement.execute();
Sign up to request clarification or add additional context in comments.

1 Comment

yup, that was it. Although I changed execute() to executeUpdate() instead. Thank you very much :)
0

executeQuery works for select statements for insert/update you should use executeUpdate. This methods returns int (record count that were inserted/updated)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.