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>

26 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

Leave a Reply

%d bloggers like this: