无法使用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 {
}
以上是 无法使用executeQuery()发出数据操作语句[重复] 的全部内容, 来源链接: utcz.com/qa/398866.html