Tem algum tutorial ou forma de adicionar novas funcionalidades como listar, pesquisar ao meu projeto? Como faço isso? Ajuda por favor

3 respostas
java
thiagobarth

Minhas classes :

package dao;

import factory.ConnectionFactory;

import modelo.Usuario;

import java.sql.*;

import java.sql.PreparedStatement;

public class UsuarioDAO {

private Connection connection;

Long id;

String nome;

String cpf;

String email;

String telefone;

public UsuarioDAO(){

this.connection = new ConnectionFactory().getConnection();

}

public void adiciona(Usuario usuario){

String sql = INSERT INTO usuario(nome,cpf,email,telefone) VALUES(?,?,?,?);

try {

PreparedStatement stmt = connection.prepareStatement(sql);

stmt.setString(1, usuario.getNome());

stmt.setString(2, usuario.getCpf());

stmt.setString(3, usuario.getEmail());

stmt.setString(4, usuario.getTelefone());

stmt.execute();

stmt.close();

}

catch (SQLException u) {

throw new RuntimeException(u);

}
}

}

package modelo;

public class Usuario {

Long id;

String nome;

String cpf;

String email;

String telefone;

public String getCpf() {

return cpf;

}

public void setCpf(String cpf) {

this.cpf = cpf;

}

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;
}
public Long getId() {
    return id;
}
public void setId(Long id) {
    this.id = id;
} 
public String getNome() { 
    return nome;
} 
public void setNome(String nome) { 
    this.nome = nome;
} 
public String getTelefone() { 
    return telefone;
} 
public void setTelefone(String telefone) { 
    this.telefone = telefone;
}

}
Desde já agradeço

3 Respostas

I

Você sabe escrever declarações SQL? Se não, como sugestão, podes visitar:

1 - W3Schools - Learn SQL;
2 - Bóson Treinamentos - Playlist de SQL no MySQL.

thiagobarth

sei

I

Um exemplo (simplista) de listagem:

public List<Usuario> listar() throws SQLException {
	List<Usuario> usuarios = new Arraylist<>();
	String stringSQL = "SELECT * FROM usuario";
	
	try(PreparedStatement pstmt = connection.prepareStatement(stringSQL)){
		try(ResultSet rstSet = pstmt.executeQuery()){
			while(rstSet.next()){
				Usuario usuario = new Usuario();
				usuario.setId(rstSet.getLong("id"));
				usuario.setNome(rstSet.getString("nome"));
				usuario.setCpf(rstSet.getString("cpf"));
				usuario.setEmail(rstSet.getString("email"));
				usuario.setTelefone(rstSet.getString("telefone"));
				
				usuarios.add(usuario);
			}
		}
	}
	return usuarios;
}

No YouTube tem bastante coisa…, mas tem que saber filtra, porque tem coisas que funcionam, mas não estão codificadas de acordo com as boas práticas.

Criado 12 de junho de 2020
Ultima resposta 13 de jun. de 2020
Respostas 3
Participantes 2