How to connect to MS SQL Server database from your Android App? – complete steps

This video shows the detailed steps to install and configure the MS SQL Server and Microsoft SQL Server Management Studio on your machine.

It shows the steps of how to boot up the (start) SQL services and then enable it (in SQL Server Configuration) to listen on a tcp/ip port. It uses local ip address and default port to connect to the SQL Server.

Later it shows how to use MS SQL Server Management Studio (SSMS) to create a new login ID (and password). It uses the new credentials to create new database and table and insert values in it.

Then it switches to Android Studio to show in simple steps of how to develop an App to interact with the MS SQL Server and database. It implements the required driver in the App’s gradle file of the project. It defines the required INTERNET permission in the manifest file. And then in java code it creates a Connection which is used for quering to the database.

For any questions, suggestions or appreciations, please reach out to us at:
https://programmerworld.co/contact/ or write to us at: programmerworld1990@gmail.com

Java code:

package com.example.mymssqlserverdatabaseconnection;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.TextView;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MainActivity extends AppCompatActivity {

    private TextView textView;

    private static String ip = "192.168.1.101";
    private static String port = "1433";
    private static String Classes = "net.sourceforge.jtds.jdbc.Driver";
    private static String database = "testDatabase";
    private static String username = "test";
    private static String password = "test";
    private static String url = "jdbc:jtds:sqlserver://"+ip+":"+port+"/"+database;

    private Connection connection = null;

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

        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.INTERNET}, PackageManager.PERMISSION_GRANTED);
        textView = findViewById(R.id.textView);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        try {
            Class.forName(Classes);
            connection = DriverManager.getConnection(url, username,password);
            textView.setText("SUCCESS");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            textView.setText("ERROR");
        } catch (SQLException e) {
            e.printStackTrace();
            textView.setText("FAILURE");
        }
    }

    public void sqlButton(View view){
        if (connection!=null){
            Statement statement = null;
            try {
                statement = connection.createStatement();
                ResultSet resultSet = statement.executeQuery("Select * from TEST_TABLE;");
                while (resultSet.next()){
                    textView.setText(resultSet.getString(1));
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        else {
            textView.setText("Connection is null");
        }
    }
}

Manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mymssqlserverdatabaseconnection">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Gradle File

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    defaultConfig {
        applicationId "com.example.mymssqlserverdatabaseconnection"
        minSdkVersion 23
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    implementation 'net.sourceforge.jtds:jtds:1.3.1'
}




Layout XML file:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="167dp"
        android:layout_marginTop="109dp"
        android:text="Hello World!"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="150dp"
        android:layout_marginTop="115dp"
        android:onClick="sqlButton"
        android:text="@string/sql"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

43 comments

  1. Would there be a different implementation for Mac users? I was trying to follow along the tutorial but at the end I was unsuccessful connecting to my database.

    1. No, for Mac also the concept will remain same. Though the driver may not work in the Emulator if Mac OS is blocking it (which is very unlikely from my understanding). To test this you can try to run it directly on a real phone.

      Good Luck
      Programmer World

  2. I have MSSQL SERVER Express installed on my computer and SQL Server Agent does not work. Is it mandatory that SQL server agent should run.
    Thank you in advance

    1. Yes, it will be mandatory for the SQL server to be running. Otherwise when the client (Android App in this case) tries to communicate with the server, it will not be able to communicate as the server is not running. Also, please ensure that the server is able to listen on the IP (address) and port number to which the Android App is communicating to.

      I hope the above helps in answering your question.

      Cheers
      Programmer World

  3. Great!!!!!. Right now I received the data from MS SQL server. Thank You.
    Only one question: I receive always exception on textView.setText. This is not critical, because I need to receive and send data to SQL but how can I escape this error?
    Thank You for the great help.

    1. What is the exception? I hope you have correctly defined and associated the textView variable with the right widget in the layout.

      Cheers
      Programmer World

  4. Hi,
    I’m trying to connect to a database hosted in azure using your code. I switch your “String url” with the one provided by azure and always keep sending me Failure when running the program.
    Any suggestions I’m kinda lost.

    Thank You,

    1. Maybe I can help, I also have similar project (using Microsot azure database).

      The url should be changed into this:
      String url = “jdbc:jtds:sqlserver://.database.windows.net:1433/”;
      The rest just the same as this tutorial.
      It worked for me. If it doesn’t work, try changing the port number (I’m not sure what the default number, but 1433 worked fine for me).

      1. String url = “jdbc:jtds:sqlserver://server_name.database.windows.net:1433/database_name”;

  5. Dear Sir Thank you
    program is work when run on emulator but it’s not work when build APK and apply on phone?

    1. If server and phone are on same network then it should definitely work. Are you getting any error on your App (in phone)? Or is the App crashing on your phone.

      Another approach could be to try to ping the server’s ip address from your phone and see if it is reachable. My following page may help you in doing this:
      https://programmerworld.co/android/how-to-check-internet-connection-from-your-android-app/

      Cheers
      Programmer World

  6. I created the database on internet server and program it worked
    but when try on database local network does not work i think the problem in SQL Server Management Studio
    SQL Server (MSSQLSERVER) : Running
    SQL Server Agent (MSSQLSERVER) : Running
    SQL Server Browser : Running
    port sql server 1433 : open

    1. I will suggest to try pinging the database and see if it is reachable on the ip and port you are using. If it pings then check username and password. If that is also correct then it has to work. MS SQL Server has to be accessible from the Android App.

      Good Luck
      Programmer World
      https://programmerworld.co

  7. Hi
    I need one help.. i have MSSQL server DB in cloudclusters.net .. please send me one solution(Connection Query) to connect the DB from Android device……

    Thanks….

    SAJITH

    1. I think you can connect to any MS SQL database available or accessible on the network. Just make sure to put the connection attributes to the server correctly in the below line of codes:

      private static String ip = “192.168.1.101”;
      private static String port = “1433”;
      private static String Classes = “net.sourceforge.jtds.jdbc.Driver”;
      private static String database = “testDatabase”;
      private static String username = “test”;
      private static String password = “test”;
      private static String url = “jdbc:jtds:sqlserver://”+ip+”:”+port+”/”+database;

      Hope it helps.

      Cheers
      Programmer World

      1. Check if your database is accessible on the network (without trying from Android App). If it is accessible over network then it should work from the App also.

        My guess is that the mentioned error is because the database is not accessible on the network.

        Cheers
        Programmer World

  8. Hello, I have a small problem. At this point:
    try {
    Class.forName(Classes);
    connection = DriverManager.getConnection(url, username,password);
    textView.setText(“SUCCESS”);
    textView.setVisibility(View.INVISIBLE);
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    textView.setText(“ERROR”);
    textView.setVisibility(View.VISIBLE);
    } catch (SQLException e) {
    e.printStackTrace();
    textView.setText(“FAILURE”);
    textView.setVisibility(View.VISIBLE);
    }
    I get in the TextView Success.
    But when I try to execute SELECT, nothing happens. The data is not sent to or retrieved from the database. I did everything according to your video, but it still doesn’t work. Please give me some advice.

  9. It is working smoothly if app and Sql server on the same network but not working if MS SQL server and phone are not on the same network?

    1. It should work even if the App and SQL server are running on different networks. Of course the App should be able to access the IP of the server (should be able to access the database server). The speed/performance will also depend on the latency between the 2 networks. That is the ping time. If the ping time is high then there may be a bit of performance issue in working with 2 different networks. Otherwise it will be fine.

      Cheers
      Programmer World

  10. Sir,

    I tried your program, but failed to get the result despite several trials. The error message is:
    Session ‘app’: Installation did not succeed.
    The application could not be installed: SHELL_UNRESPONSIVE

    Could you kindly help me. Another query: In the sql string you mentioned only ip, port and database, not the server name. Is it not necessary to mention the server name?

    Best regards

    Fysal Usman

    1. App installation fails when there is a mismatch in min Sdk version of your App and the device’s Android version (like device’s version is older than App’s version). There could be some other similar issues, such as some configuration in your App development environment (Android Studio).

      To fix this, I will suggest that you first try to create just a dummy App and try to build and run on the device. If that succeeds then proceed with that Android Studio environment by implementing your code. If it fails then check the configuration. Most likely changing to an older version of SDK may help.

      For the other query, ip address or server name are interchangeable. So, if we use ip then server name is not required or vice versa. Both, server name and ip, are to connect to right machine over the network. So, anyone is fine to use.

      Hope above helps.

      Cheers
      Programmer World

  11. Sir,

    The above mentioned problem is somehow resolved (I don’t know how, but I reinstalled Android Studio). Now my problem is the connection failure. I get the 1st message “Error” indicating ‘ClassNotFoundException’. The net.sourceforge.jtds.jdbc.Driver is not installed in my laptop. Do I have to install it first?

    Thanks a lot Sir for your valuable help and support.

    Fysal Usman

    1. Check if the below implementation is included in the gradlle file:

      implementation ‘net.sourceforge.jtds:jtds:1.3.1’

      Refer to the source code on this webpage.

      Cheers
      Programmer World

      1. Sir,

        It is not included, but when I included the opening and ending single commas and the colon are highlighted red with comments unexpected “‘” and “no candidate found for method net”.

  12. Thank you very much Sir. It works now. There was a problem with SDK version as that mentioned in your gradle.build was not in my Android, so there was error, but I resolved it. I will ever remain grateful to you for your help and support.

  13. Sir,

    Is it possible to create a combobox or textvox suggestion list, retrieving data from a table in the sql database, in this android app as we create in vb.net or c#?

    1. Yes, it is easily possible. In fact there are ample of examples available on my website: https://programmerworld.co/android/

      Some of the quick examples which you can refer are:
      https://programmerworld.co/android/create-a-simple-business-app-using-sql-lite-database-in-android-studio-for-beginners/
      https://programmerworld.co/android/how-to-develop-an-android-app-for-your-retail-business-b2c-using-firebase-database-source-code/

      Hope above helps.

      Cheers
      Programmer World

Leave a Reply

%d bloggers like this: