Jad J
Jad J

Reputation: 91

Unable to INSERT rows into MySQL Database

I have a datebase lyrics with a table lyrics1, and with the code below I want to insert a row into lyrics1.

But when I go back to the mysql client and do describe lyrics1, it hasn't updated.

I get no error, it connects to the database fine. At least I don't get error saying it was unable to.

connectToDB();

ok.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        try {

            String query = "INSERT INTO lyrics1(name, artist) values(?, ?)";
            PreparedStatement statement = connection.prepareStatement(query);
            statement.setString(1, nameOfSong.getText()); // set input parameter 2
            statement.setString(2, artist.getText());   
            ResultSet rs = statement.executeQuery("SELECT * FROM lyrics1");
            while (rs.next()){
                System.out.println(rs.getString(1));
            }
            rs.close();
            statement.close();
            connection.close();

        } catch (SQLException insertException) {
            displaySQLError(insertException);
        } 
        internalFrame.dispose();
    }
});

Upvotes: 3

Views: 332

Answers (1)

user177800
user177800

Reputation:

you are never actual executing the INSERT statement, you just create it and never actual execute it. You are executing a SELECT but nothing actually sends the INSERT statement to the server.

You need to first call statement.executeUpdate() it will return the number of rows affected, most of the time you want to check that this is equal to 1 for INSERT and more than ZERO for UPDATE and DELETE.

Upvotes: 4

Related Questions