无法使用executeQuery()发出数据操作语句 [英] Can not issue data manipulation statements with executeQuery()

查看:1986
本文介绍了无法使用executeQuery()发出数据操作语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 com.mysql.jdbc.Driver

我需要插入和获取id。
我的查询:

I need insert and get id. My query:

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

错误 -


无法通过executeQuery()发布数据操作
语句

Can not issue data manipulation statements with 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 {

    }

这篇关于无法使用executeQuery()发出数据操作语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆