Tenho uma tabela de clientes e quero pegar o ultimo id da tabela que é um campo autoincrement.
To fazendo o código abaixo mas ta dando erro, alguem tem uma dica?
[color=darkblue] public int getUltimoId() throws SQLException{
String sql = “SELECT MAX(ID) FROM CLIENTES”;
PreparedStatement stmt = (PreparedStatement) connection.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
int lastId = rs.getInt(“id”);
rs.close();
stmt.close();
return lastId;
}[/color]
dá esso erro:
[color=darkred]
java.sql.SQLException: Column ‘id’ not found.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1144)
at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2794)
at webwork.dao.ClienteDAO.getUltimoId(ClienteDAO.java:118)
at webwork.fachada.Fachada.getLastIdCli(Fachada.java:360)
at webwork.teste.ListaClienteTeste.main(ListaClienteTeste.java:26)
[/color]
Diz que a coluna id nao existe. Mas ela existe. no meu metodo listar faço coisa parecida e funciona:
[color=darkblue]public List<Cliente> listar() throws SQLException{
String sql = "SELECT * FROM CLIENTES";
PreparedStatement stmt = (PreparedStatement) connection.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
List<Cliente> clientes = new ArrayList<Cliente>();
while(rs.next()){
Cliente cliente = new Cliente();
cliente.setId(rs.getInt("id"));
clientes.add(cliente);
}
rs.close();
stmt.close();
return clientes;
}[/color]
