无法使用executeQuery()发出数据操作语句[重复]


问题内容

我用 com.mysql.jdbc.Driver

我需要插入并获取ID。我的查询:

INSERT INTO Sessions(id_user) VALUES(1);
SELECT LAST_INSERT_ID() FROM Sessions LIMIT 1;

错误-

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

如何插入并获取ID?


问题答案:

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 {

    }