Duvida PreparedStatement

6 respostas
A

e ai galera blz.

tem algum metodo do preparedStatement que me retorne o codigo autoIncrement de uma linha que acabei de inseri no banco de dados?

vou tentar explicar melhor.
tenho uma tabela Cliente no banco com os seguinte atributos
codigo (Integer) auto increment
data2(Date)

quando eu fosse inserir um cliente eu queria q no proprio metodo de inserção ele me retornasse o codigo do cliente q acabou de ser inserido no banco. tem jeito???

vou postar meu metodo de inserção.

public void create(Object obj) throws IOException {
if (obj instanceof negocio.Cliente) {
            negocio.Cliente cliente = (negocio.Cliente) obj;

            File file = new File("c:/Arquivos de programas/sql.properties");
            Properties properties = new Properties();
            FileInputStream fis = null;
            PreparedStatement stmt = null;

            try {
                Conectar conn = new Conectar();
                connection = conn.Getconectar();

                fis = new FileInputStream(file);
                properties.load(fis);
                fis.close();

                stmt = connection.prepareStatement(properties.getProperty("CLIENTE_CREATE"));

                stmt.setInt(1, cliente.getEndereco().getCodigo());
                stmt.setDate(2, new java.sql.Date(cliente.getData().getTime()));
                
                stmt.executeUpdate();
            } catch (IllegalAccessException ex) {
                ex.printStackTrace();
            } catch (InstantiationException ex) {
                ex.printStackTrace();
            } catch (SQLException e) {
                throw new IOException("ClienteDAO CREATE: " + e);
            } finally {
                close(stmt, null, connection);
            }
        }
    }
desde já agradeço

6 Respostas

Andre_Fonseca
andrertd:
e ai galera blz.

tem algum metodo do preparedStatement que me retorne o codigo autoIncrement de uma linha que acabei de inseri no banco de dados?

vou tentar explicar melhor.
tenho uma tabela Cliente no banco com os seguinte atributos
codigo (Integer) auto increment
data2(Date)

quando eu fosse inserir um cliente eu queria q no proprio metodo de inserção ele me retornasse o codigo do cliente q acabou de ser inserido no banco. tem jeito???

vou postar meu metodo de inserção.

public void create(Object obj) throws IOException {
if (obj instanceof negocio.Cliente) {
            negocio.Cliente cliente = (negocio.Cliente) obj;

            File file = new File("c:/Arquivos de programas/sql.properties");
            Properties properties = new Properties();
            FileInputStream fis = null;
            PreparedStatement stmt = null;

            try {
                Conectar conn = new Conectar();
                connection = conn.Getconectar();

                fis = new FileInputStream(file);
                properties.load(fis);
                fis.close();

                stmt = connection.prepareStatement(properties.getProperty("CLIENTE_CREATE"));

                stmt.setInt(1, cliente.getEndereco().getCodigo());
                stmt.setDate(2, new java.sql.Date(cliente.getData().getTime()));
                
                stmt.executeUpdate();
            } catch (IllegalAccessException ex) {
                ex.printStackTrace();
            } catch (InstantiationException ex) {
                ex.printStackTrace();
            } catch (SQLException e) {
                throw new IOException("ClienteDAO CREATE: " + e);
            } finally {
                close(stmt, null, connection);
            }
        }
    }
desde já agradeço

Oi

Caso você esteja usando MySQL deve funcionar colocando as linhas abaixo após o INSERT

stmt.executeUpdate();

stmt = connection.prepareStatement("CALL IDENTITY()");
...
ResultSet result = stmt.executeQuery();
int id = result.getInt(1);
A

o sistema diz q não reconhece o IDENTITY()

Andre_Fonseca

qual Banco de Dados está usando?

A

My sql

M

use

stmt = connection.prepareStatement(properties.getProperty("CLIENTE_CREATE", PreparedStatement.RETURN_GENERATED_KEYS));Declare uma variável do tipo ResultSet e depois de inserir//recupera o Id: rs = pstmt.getGeneratedKeys(); rs.next(); bean.setId(rs.getInt(1));

A

puta cara valeu mesmo em.. me quebro um galhão... mas deu um erro quando fui passar PreparedStatement.RETURN_GENERATED_KEYS dentro do metodo getProperty. então fiz desse jeito e deu certo do mesmo jeito..

mais uma vez agradeço pela ajuda.

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Properties;
import java.util.Vector;

/**
 *
 * @author André
 */
public class ClienteDAO extends DAO {

    private Connection connection = null;

    @Override
    public void create(Object obj) throws IOException {
        if (obj instanceof negocio.Cliente) {
            negocio.Cliente cliente = (negocio.Cliente) obj;

            File file = new File("c:/Arquivos de programas/sql.properties");
            Properties properties = new Properties();
            FileInputStream fis = null;
            PreparedStatement stmt = null;

            try {
                Conectar conn = new Conectar();
                connection = conn.Getconectar();

                fis = new FileInputStream(file);
                properties.load(fis);
                fis.close();

                stmt = connection.prepareStatement(properties.getProperty("CLIENTE_CREATE"));

                stmt.setInt(1, cliente.getEndereco().getCodigo());
                stmt.setDate(2, new java.sql.Date(cliente.getData().getTime()));
                stmt.setString(3, cliente.getNome());
                stmt.setString(4, cliente.getTelefone());
                stmt.setString(5, cliente.getFax());
                stmt.setString(6, cliente.getCnpj());
                stmt.setString(7, cliente.getInscricao());
                stmt.setString(8, cliente.getContato());
                stmt.setString(9, cliente.getObs());

                stmt.executeUpdate();
                
                ResultSet rs  = stmt.getGeneratedKeys();
                rs.next();
                int chave = rs.getInt(1);
             
            } catch (IllegalAccessException ex) {
                ex.printStackTrace();
            } catch (InstantiationException ex) {
                ex.printStackTrace();
            } catch (SQLException e) {
                throw new IOException("ClienteDAO CREATE: " + e);
            } finally {
                close(stmt, null, connection);
            }
        }
    }
}
Criado 29 de agosto de 2009
Ultima resposta 30 de ago. de 2009
Respostas 6
Participantes 3