0
I’m running this code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.caelum.jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestaInsercao {
public static void main(String[] args) throws SQLException {
Connection connection = DataBase.getConnection();
String nome = "Notebook";
String descricao = "Notebook core i5";
String sql = "insert into produto (nome, descricao) values (?,?)";
PreparedStatement comando = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
comando.setString(1, nome);
comando.setString(2, descricao);
boolean resultado = comando.execute();
System.out.println(resultado);
ResultSet resultSet = comando.getGeneratedKeys();
while (resultSet.next()) {
String id = resultSet.getString("id");
System.out.println("Chave gerado: " + id);
}
resultSet.close();
comando.close();
connection.close();
}
}
And I’m getting the following Sqlexception on the line comando.getString("id")
:
run: false Exception in thread "main" java.sql.Sqlexception: Column 'id' not found. at com.mysql.jdbc.SQLError.createSQLException(Sqlerror.java:1074) at com.mysql.jdbc.SQLError.createSQLException(Sqlerror.java:988) at com.mysql.jdbc.SQLError.createSQLException(Sqlerror.java:974) at com.mysql.jdbc.SQLError.createSQLException(Sqlerror.java:919) at com.mysql.jdbc.ResultSetImpl.findColumn(Resultsetimpl.java:1167) at com.mysql.jdbc.ResultSetImpl.getString(Resultsetimpl.java:5733) at br.com.Caelum.jdbc.Testainsercao.main(Testainsercao.java:33) C: Users Bahia Appdata Local Netbeans Cache 8.2 executor-snippets run.xml:53: Java returned: 1 BUILD FAILURE (total time: 0 seconds)
I know that There you are saying that you are not finding the id column, but it exists, and when I go to Mysql Workbench and make a select in my table, it shows that the product has been added, even showing false and giving Exception in java
was. can you explain to me why ?
– RickPariz
The bank was creating its key as int or long and you were expecting a string in return basically for that. The
resultSet.getLong(1);
takes the return of the first column of the table, index 1.– Paulo H. Hartmann