How to link an Android app to MS SQL Server 2008?

Hey everyone! I’m just starting out with Android development and I’m having trouble getting my app to talk to a Microsoft SQL Server 2008 database. I’m using the jtds-1.3.1.jar driver, but no luck so far.

Every time I try to connect, I get this error: Network error IOException: connection time out

I’m working in Eclipse Juno. Here’s a simplified version of what I’ve got:

public class DatabaseConnector extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_screen);
        tryDatabaseConnection();
    }

    private void tryDatabaseConnection() {
        TextView statusText = findViewById(R.id.status);
        String dbUrl = "jdbc:jtds:sqlserver://192.168.1.100:1433;DatabaseName=MyShop";
        String dbDriver = "net.sourceforge.jtds.jdbc.Driver";
        String dbUser = "ShopUser";
        String dbPass = "ShopPass123";

        try {
            Class.forName(dbDriver);
            Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPass);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT TOP 1 * FROM Products");

            if (rs.next()) {
                statusText.setText("Connected: " + rs.getString(1));
            }
        } catch (Exception e) {
            statusText.setText("Error: " + e.getMessage());
        }
    }
}

Any ideas what I’m doing wrong? Thanks in advance!

Have you considered using an ORM (Object-Relational Mapping) library like Room or GreenDAO? These can simplify database operations and provide a more Android-friendly approach. They abstract away much of the complexity of direct JDBC connections.

Additionally, for security reasons, it’s generally not recommended to connect directly to a remote database from a mobile app. Instead, you might want to set up a RESTful API on your server that handles database operations. Your Android app can then communicate with this API using libraries like Retrofit or Volley.

If you must use direct SQL Server connection, ensure your server allows remote connections and that all necessary ports are open. Also, consider running your database operations on a background thread to prevent ANR (Application Not Responding) errors.

yo, have u tried running ur app on a different network? sometimes corporate wifi can block these connections. also, double-check ur server’s IP - maybe it changed? if nothing works, u might wanna look into using a REST API instead. easier to set up and more secure, tbh.

hey there! have u tried using a web service instead of connecting directly? it might be easier and safer. also, check if ur server’s firewall is blocking the connection. maybe try increasing the timeout in ur connection string too? just some ideas to explore. let me know if any of those help!