简体   繁体   中英

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();
    }
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM