2

I have a problem when I try to execute my query in Java. when I try to add an object to my database in SQL, it gives me a error saying that the instruction don't send the result set. When I execute the query in sql server, it work fine and it insert the object. Please help me.

public void addAlbum(String title, double price, String genre, String date, String home, String image) {

int number = getData().size();

boolean isThere = false;    

Statement statement;

for(int i = 0; i < getData().size();i++){

    if(getData().get(i).getTitle().equals(title)){

        isThere = true;

    }

}

if(!isThere){

    try{


        statement = connexion.createStatement();
        String query = "use albums INSERT INTO dbo.Album(Album.artist_number, title, price, genre, date, home, image) VALUES(" + number + ", '" + title + "', " + price + ", '" + genre + "', '" + date + "', '" + home + "', '" + image + "')";

        statement.executeQuery(query);

        getData().add(new Album(String.valueOf(number),title, price, genre, date, home));

        fireTableRowsInserted(getData().size() -1, getData().size() -1);

    }catch(SQLException e){

        JOptionPane.showMessageDialog(null,
                "Error "
                        + e.getMessage(), "Result",
                JOptionPane.ERROR_MESSAGE);

    }       


}else{

    JOptionPane.showMessageDialog(null,
            "There is already an album with this name", "Result",
            JOptionPane.ERROR_MESSAGE);

}
}
2
  • You have a SQL injection vulnerability. Commented Sep 30, 2012 at 19:26
  • use albums INSERT INTO probably is probably not valid without a semicolon, and very well may not work with one. Normally you would not have a use DBNAME statement, that would be part of your connection string. Also you have SQL injection Bobby O'Tables. Commented Sep 30, 2012 at 19:27

1 Answer 1

2

You need to use Statement.executeUpdate(String) for INSERT. Statement.executeQuery(String) is for SELECT.

PreparedStatements are better, easier and safer. Using Prepared Statements.

Sign up to request clarification or add additional context in comments.

1 Comment

And avoid mixing your UI code with DB code! Try using a design pattern such as Model-View-Controller

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.