无法在Java中执行MySQL删除语句

Zer*_*tas 3 java mysql jdbc

我试图让这段代码运行并删除MySQL数据库中的某条记录,但是我收到此错误:

SQLException: Can not issue data manipulation statements with executeQuery().
SQLState:     S1009
VendorError:  0
Run Code Online (Sandbox Code Playgroud)

这是我目前的代码:

package stringStuff;

import java.io.File;
import java.util.regex.*;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class REGGY {

    /**
     * @param args
     */

    Connection connection;

    public REGGY() {
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
        } catch (Exception e) {
            System.err.println("Unable to find and load driver");
            System.exit(1);
        }
    }

    private void displaySQLErrors(SQLException e) {
        System.out.println("SQLException: " + e.getMessage());
        System.out.println("SQLState:     " + e.getSQLState());
        System.out.println("VendorError:  " + e.getErrorCode());
    }

    public void connectToDB() {
        try {
            connection = DriverManager
                    .getConnection("the connection works :P");
        } catch (SQLException e) {
            displaySQLErrors(e);
        }
    }

    public void executeSQL() {
        try {
            Statement statement = connection.createStatement();

            ResultSet rs = statement
                    .executeQuery("DELETE FROM content_resource WHERE RESOURCE_ID LIKE '%Hollow%'");



            rs.close();
            statement.close();
            connection.close();
        } catch (SQLException e) {
            displaySQLErrors(e);
        }
    }

    public static void main(String[] args) {

        String cool = new File(
                "/group/a45dea5c-ea09-487f-ba1c-be74b781efb1/Lessons/Hollowbody 5.gif")
                .getName();

        System.out.println(cool);

        REGGY hello = new REGGY();

        hello.connectToDB();
        hello.executeSQL();

        // TODO Auto-generated method stub

    }

}
Run Code Online (Sandbox Code Playgroud)

我能够运行select*查询没问题,但是当我尝试运行DELETE查询时它不会让我.我已经在MySQL工作台中运行了这个命令并且它可以工作,当我使用Java时它就不起作用了.

gsi*_*rin 7

更改

ResultSet rs = statement.executeQuery("DELETE FROM content_resource WHERE RESOURCE_ID LIKE '%Hollow%'");
Run Code Online (Sandbox Code Playgroud)

int deletedRows = statement.executeUpdate("DELETE FROM content_resource WHERE RESOURCE_ID LIKE '%Hollow%'");
Run Code Online (Sandbox Code Playgroud)

正如其他人所说,executeQuery()应该用于返回数据的语句,通常是select语句.对于insert/update/delete语句,您应该使用executeUpdate().


cor*_*iKa 6

你用executeUpdate()它代替.

executeQuery()仅适用于返回数据的语句.executeUpdate是那些不会返回日期(更新,插入,删除,我相信添加/删除表,约束,触发器等)的东西.