Aluno Java Class with JDBC CRUD Operations for Student Management
Aluno Class in Java: Student Management with JDBC
The following Java class, Aluno, represents a student and provides methods to create, read, update and delete records in the aluno table using JDBC.
package classes;
import java.sql.*;
import classes.Conexao;
public class Aluno {
private int idaluno = 0;
private String nome = "";
private String endereco = "";
private String cidade = "";
private String estado = "";
private String pais = "";
private String cep = "";
public int getIdaluno() {
return idaluno;
}
public void setIdaluno(int idaluno) {
this.idaluno = idaluno;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getCidade() {
return cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public String getPais() {
return pais;
}
public void setPais(String pais) {
this.pais = pais;
}
public void alterar() {
String q = "update aluno set nome = '" + nome + "', endereco = '"
+ endereco + "', cep = '" + cep + "' where idaluno = "
+ idaluno;
Connection cn = Conexao.getConnection();
try {
Statement st = cn.createStatement();
st.executeUpdate(q);
} catch (SQLException e) {
e.getMessage();
}
}
public void incluir() {
String q = "insert into aluno(nome) values('" + nome + "')";
Connection cn = Conexao.getConnection();
try {
Statement st = cn.createStatement();
st.executeUpdate(q);
} catch (SQLException e) {
e.getMessage();
}
}
public void excluir() {
String q = "delete from aluno where idaluno = " + idaluno;
Connection cn = Conexao.getConnection();
try {
Statement st = cn.createStatement();
st.executeUpdate(q);
} catch (SQLException e) {
e.getMessage();
}
}
public void buscar() {
String q = "select nome, endereco, cep from aluno where idaluno = "
+ idaluno;
Connection cn = Conexao.getConnection();
try {
Statement st = cn.createStatement();
ResultSet rs = st.executeQuery(q);
if (rs.next()) {
nome = rs.getString("nome");
endereco = rs.getString("endereco");
cep = rs.getString("cep");
} else {
nome = "";
endereco = "";
cep = "";
}
} catch (SQLException e) {
e.getMessage();
}
}
public ResultSet listar() {
String q = "select idaluno, nome from aluno;";
Connection cn = Conexao.getConnection();
ResultSet rs = null;
Statement st = null;
try {
st = cn.createStatement();
rs = st.executeQuery(q);
} catch (SQLException e) {
e.getMessage();
}
return rs;
}
}Notes
- The alterar() method updates name, address and postal code.
- incluir() inserts a new student using the name.
- buscar() loads a student's data by idaluno.
- listar() returns all students' IDs and names.