无法使用executeQuery()发出数据操作语句

Med*_*tor 18 java mysql sql database jdbc

我用 com.mysql.jdbc.Driver

我需要插入并获取id.我的查询:

INSERT INTO Sessions(id_user) VALUES(1);
SELECT LAST_INSERT_ID() FROM Sessions LIMIT 1;
Run Code Online (Sandbox Code Playgroud)

错误 -

无法使用executeQuery()发出数据操作语句

如何插入并获取ID?

Vin*_*lds 20

您将需要使用executeUpdate()方法来执行INSERT语句,而您需要使用executeQuery()方法来执行SELECT语句.这是由于JDBC规范对其用法的要求:

Statement.executeQuery()的Java API文档:

执行给定的SQL语句,该语句返回单个ResultSet对象.

参数:

sql - 要发送到数据库的SQL语句,通常是静态SQL SELECT语句

并从Statement.executeUpdate()的Java API文档中:

执行给定的SQL语句,该语句可以是INSERT,UPDATE或DELETE语句,也可以是不返回任何内容的SQL语句,例如SQL DDL语句.

参数:

sql - 一种SQL数据操作语言(DML)语句,例如INSERT,UPDATE或DELETE; 或者不返回任何内容的SQL语句,例如DDL语句.

您的代码(此处发布的伪代码)应显示为:

statement.executeUpdate("INSERT INTO Sessions(id_user) VALUES(1)"); // DML operation
statement.executeQuery("SELECT LAST_INSERT_ID()"); // SELECT operation
Run Code Online (Sandbox Code Playgroud)

当然,MySQL文档演示了如何为AUTO_INCREMENT列执行相同的活动,这显然是您所需要的.

如果你需要在同一个事务中一起执行它们,可以通过一个字符串提交语句,用分号分隔它们,如下所示:

statement.execute("INSERT INTO Sessions(id_user) VALUES(1); SELECT LAST_INSERT_ID() FROM Sessions LIMIT 1;");
Run Code Online (Sandbox Code Playgroud)

那么你需要使用execute()方法.请注意,这取决于数据库和JDBC驱动程序为单个execute()中的批处理语句提供的支持.这在Sybase和MSSQL Server中受支持,但我不认为它在MySQL中受支持.


Vir*_*ade 7

可能你正在使用executeQuery()但是操作数据实际上需要executeUpdate()而不是executeQuery()


Med*_*tor 4

    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet generatedKeys = null;

    try {
        connection = m_Connection;
        preparedStatement = (PreparedStatement) connection.prepareStatement(qString, Statement.RETURN_GENERATED_KEYS);

        // ...

        int affectedRows = preparedStatement.executeUpdate();
        if (affectedRows == 0) {
            throw new SQLException("Creating user failed, no rows affected.");
        }

        generatedKeys = preparedStatement.getGeneratedKeys();
        int id = -1;
        if (generatedKeys.next()) {
            id = generatedKeys.getInt(1);
            id = -1;
        } else {
            throw new SQLException("Creating user failed, no generated key obtained.");
        }
    } finally {

    }
Run Code Online (Sandbox Code Playgroud)