TimeOut Android and SQL Server connection using JDBC / JTDS

0

I would like to limit a time for the connection. Whenever it does not find Host to connect, it keeps trying and slows down.

Here is the code:

@SuppressLint("NewApi")
public Connection CONN() {

/*Properties props = new Properties();
props.setProperty("user", "dbuser");
props.setProperty("password", "dbpassword");
props.setProperty(OracleConnection.CONNECTION_PROPERTY_THIN_NET_CONNECT_TIMEOUT, "2000");*/

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
        .permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
    Class.forName(classs);
    ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
            + "databaseName=" + db + ";user=" + un + ";password="
            + password + ";namedPipe=true;loginTimeout=5;socketTimeout=1";

/*Properties properties = new Properties();
properties.put("connectTimeout", "2000");*/
    DriverManager.setLoginTimeout(5);
    conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
    Log.e("ERRO", se.getMessage());
} catch (ClassNotFoundException e) {
    Log.e("ERRO", e.getMessage());
} catch (Exception e) {
    Log.e("ERRO", e.getMessage());
}
return conn;
}
    
asked by anonymous 28.11.2017 / 21:45

1 answer

-1

I do not know if you already have a solution for what you wanted, but you could always try this solution given here: link

Edit.

I was able to resolve my situation by creating a method to do this check.

public boolean checkConnetion()
{
    boolean success;
    try
    {
        _driver = "net.sourceforge.jtds.jdbc.Driver";
        _conString = "jdbc:jtds:sqlserver://" + GlobalVars.SQLServerInfo.get("server") + ":" + GlobalVars.SQLServerInfo.get("port") + "/" + GlobalVars.SQLServerInfo.get("dbname") +
                ";instance=" + GlobalVars.SQLServerInfo.get("instance") + ";loginTimeout=2";
        Class.forName(_driver);
        _con = DriverManager.getConnection(_conString, GlobalVars.SQLServerInfo.get("user"), GlobalVars.SQLServerInfo.get("pass"));
        _con.close();
        success = true;
    }
    catch (Exception e)
    {
        Log.d("checkConnetion", e.toString());
        success = false;
    }
    return success;
}

I have this within the Class I have to handle my queries and the like that I need for SQL, and I can call this function whenever I need to do a check.

It could also be implemented as private and test within the Class itself, but I preferred to test it on the outside, since it has to be all AsyncTask

In logcat when he can not connect, this will appear:

  

java.sql.SQLException: Network error IOException: failed to connect to /192.168.1.9 (port 1433) after 2000ms

    
02.02.2018 / 10:58