3
Classe Fabrica
import java.sql.Connection;
import java.sql.DriverManager;
public class Fabrica {
public Connection getConexao() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/teste", "root", "123");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
}
Alunodao class
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class AlunoDAO {
private Connection conn;
public void insert(String nome, int matricula) {
String sql = "insert into aluno values (?,?)";
conn = new Fabrica().getConexao();
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, nome);
ps.setInt(2, matricula);
ps.execute();
ps.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(AlunoDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void select() {
String sql = "select * from aluno";
try {
PreparedStatement ps = this.conn.prepareStatement(sql); //linha 41
ResultSet result = ps.executeQuery();
while(result.next()) {
System.out.println(result.getString("nome"));
System.out.println(result.getInt("matricula"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
MAIN CLASS
public class Principal {
public static void main(String[] args) {
AlunoDAO dao = new AlunoDAO();
dao.select(); //linha 10
}
}
ERROR: java.lang.Nullpointerexception
At Alunodao.select(Alunodao.java:41)
At Principal.main(Home.java:10)
Thank you, you helped me a lot!
– lucas