Erroneous connection of Android with SQLServer

1

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?

    
asked by Andres Henriquez 20.09.2017 в 05:12
source

3 answers

2

check since the cell phone and from instances the connection can be resolved to ping ANDRESPC, if it does not solve it, place the ip that can be seen.

try first making a connection like that in sql manager, instance ANDRESPC, username and password, if you connect, check that you can connect.

Check that port 1433 is receiving the connections and that it is configured in the connection class

    
answered by 21.09.2017 / 00:10
source
1

I think the fault you're having is that you're not using the corresponding driver. When a connection is made from java it is necessary to have the jdbc driver to be able to make calls to BBDD in case of android you should not have it.

What I do not understand is the reason why you use the SQLserver DB, because if it is only to save data you should use the android SQLite itself and in case you have to use it directly against BBDD it is dangerous to mount a webservice that filters those calls

    
answered by 20.09.2017 в 09:15
0

The error you get is generated when you call the prepareStatement() method, but the connection has a null value:

  

Attempt to invoke interface method 'java.sql.PreparedStatement   java.sql.Connection.prepareStatement (java.lang.String)

It is important to review what problem you have in the connection and validate this way when the connection has a null value:

public void consultarPaquete() {
        try {
            Connection conn = connectionBD(driver);
            if(conn != null) {
             PreparedStatement pat = conn.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();
            }else{
              Toast.makeText(getApplicationContext(), "Connection to server failed!", Toast.LENGTH_LONG).show();
            }
        }
        catch (Exception ex) {
            Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

Review the conexionBD() method, ensure the instance is correct, you might need to define the port. Check credentials Check what the message is in e.getMessage()

    
answered by 21.09.2017 в 00:27