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

我使用com.mysql.jdbc.Driver

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

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

错误 –

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

如何插入并获取ID?

您将需要使用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 

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

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

 statement.execute("INSERT INTO Sessions(id_user) VALUES(1); SELECT LAST_INSERT_ID() FROM Sessions LIMIT 1;"); 

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

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

  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 { } 

对于非选择SQL语句,您使用ExecuteNonQuery();

要获取最后插入的id,可以执行此SQL语句。

 SELECT LAST_INSERT_ID() AS last_id 

虽然这个select语句可能有一个java包装器。

链接:
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
http://wiki.bibalex.org/JavaDoc/org/bibalex/daf/handlers/dbhandler/DBConnection.html