My problem is this, I have a BD and a Java application, we forgot the BD, let's focus on the App, I created a connection to a database that SI works, very all right. Now I propose to create a method in JAVA that returns an integer, the problem that arises is
Exception in thread "main" java.lang.NullPointerException at Conexion.Conexion.contar_num_personajes (Conexion.java:58) at Test.Test.main (Test.java:34)
I have looked and should not give me that, it is something I am new to and I strive to learn every day more, it gives me the exception of NullPointer
package Conexion;
import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Conexion {
private Connection co;
public Conexion() {
this.co = null;
}
public Connection get_conection() {
return this.co;
}
public boolean conectar() throws ClassNotFoundException, SQLException {
/*
Connection c = null;
Class.forName("com.mysql.jdbc.Driver");
//el metodo getConnection() hay que adaptarlo para conectarlo a mi base de daots de hostinguer
c = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306//");
Statement stm = c.createStatement();
System.out.println("Conectado correctamente a la Base de Datos de 'League Of Leguends'");
this.co = c;
*/
boolean conectado = false;
Connection c = null;
Class.forName("com.mysql.jdbc.Driver");
c = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/LEAGUE_OF_LEGENDS", "miusuario", "micontraseña");
Statement stm = c.createStatement();
conectado = true;
System.out.println("Conectado correctamente a la Base de datos : LEAGUE OF LEGUENDS");
if (conectado == true) {
return true;
} else {
return false;
}
}
public int contar_num_personajes() throws SQLException {
int n = 0;
Connection dbConnection = get_conection();
Statement stm = dbConnection.createStatement();
// almaceno resultado de consulta en ResultSet
ResultSet rs = stm.executeQuery("SELECT count(*) FROM personajes");
// chequeo que el result set no sea vacío, moviendo el cursor a la
// primer fila. (El cursor inicia antes de la primer fila)
if (rs.next()) {
//Si hay resultados obtengo el valor.
n = rs.getInt(1);
}
// libero recursos
stm.close();
dbConnection.close();
return n;
}
}