3

我正在尝试运行此代码并删除 MySQL 数据库中的某个记录,但出现此错误:

SQLException: Can not issue data manipulation statements with executeQuery().
SQLState:     S1009
VendorError:  0

这是我目前拥有的代码:

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

    }

}

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

4

6 回答 6

7

你用executeUpdate()它代替。

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

于 2012-07-30T17:36:43.277 回答
7

改变

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

int deletedRows = statement.executeUpdate("DELETE FROM content_resource WHERE RESOURCE_ID LIKE '%Hollow%'");

正如其他人所说,executeQuery() 应该用于返回数据的语句,通常是 select 语句。对于插入/更新/删除语句,您应该改用 executeUpdate()。

于 2012-07-30T17:38:16.033 回答
3

要执行 DML 语句(插入、创建或删除),您必须使用executeUpdate(). 不是executeQuery()

于 2012-07-30T17:37:20.120 回答
2

使用executeUpdate而不是executeQuery. JDBC 很沮丧,因为 delete 语句没有像executeQuery预期的那样返回记录集。

于 2012-07-30T17:37:18.560 回答
1

使用execute而不是executeQuery.

据我所知,如果您正在执行返回结果集的查询(例如) ,executeQuery则必须使用。select

于 2012-07-30T17:39:06.593 回答
0

确保您已设置DELETE语句的权限。出于安全目的,某些用户将不允许使用某些命令。

于 2012-07-30T17:37:03.407 回答