I am starting to program a small project in Android Studio. I want to make a query to the base, in case the connection fails it gives me a message in a Toast:
Network error IDException: failed to connect to /ANDRESPC\SQLEXPRESS
(port 1433): connect failed: ENETUNREACH (Network is unreachable)
Where /ANDRESPC\SQLEXPRESS
is the instance of sqlexpress
Attempt to invoke interface method
'java.sql.PreparedStatementjava.sql.Conn
ection.prepareStatement(java.lang.String)'
on a null object reference
The connection code is this:
public Connection conexionBD() {
Connection conexion = null;
try{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
conexion = DriverManager.getConnection("jdbc:jtds:sqlserver://ANDRESPC\SQLEXPRESS;databasename=speedex1;user=andres;password=123;");
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
return conexion;
}
The code of the query code is this:
public void consultarPaquete() {
try {
PreparedStatement pat = conexionBD().prepareStatement("SELECT es.estado, en.fechaLlegada, t.transporte, en.precioTotal FROM estado es, envio en, medioTransporte t WHERE es.estadoId = en.estadoId AND t.transporteId = en.transporteId AND en.envioId = ?");
pat.setInt(1, Integer.parseInt(envio));
pat.executeUpdate();
ResultSet rs = pat.executeQuery();
if(rs.next()){
//asignandole a los atributos de la clase
estado = rs.getString(1);
fecha = rs.getString(2);
transporte = rs.getString(3);
precio = rs.getDouble(4);
}
//cerrando conexion
pat.close();
Toast.makeText(getApplicationContext(), "Consulta exitosa", Toast.LENGTH_LONG).show();
}
catch (Exception ex) {
Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
And the code to execute this is in a class that is activated in the event onClick
of a button:
public void ejecutarConsulta(View view) {
consultarPaquete();
System.out.println("El estado es " + estado + "/n" + "La fecha es " + fecha + "/n" + "El tipo de transporte es " + transporte + "/n" + "El precio es " + precio);
}
My question is Why is it wrong? I was wrong in the way to make the connection or to make the query?