Skip to main content

Connection between Android and MS SQL Server Database.

Connection between Android and MS SQL Database.

In this post we will learn about the MS SQL Server Connection with Android Application. For this concept we will use JTDS.jar library in our Android application.

Download jtds library using this link: Jtds library.

We will learn this using step by step.

Step 1: Next we will create our MS SQL Database. My Database name is DemoDB. It is a Microsoft SQL 2012 Database.

Step2: Now Open Android Studio and Add JTDS.jar library in to your project.

Step 3: Now lets start design the app

res > layout > activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
   
android:orientation="vertical"
   
tools:context=".MainActivity">

    <
TextView
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:textSize="28dp"
       
android:text="Hello World!"
       
android:gravity="center"
       
/>
<
Button
   
android:layout_width="match_parent"
   
android:layout_height="wrap_content"
   
android:id="@+id/DBConnect"
   
android:layout_margin="15dp"
   
android:background="@color/colorPrimaryDark"
   
android:textColor="#FFFFFF"
   
android:textSize="16dp"
   
android:text="Connect with MS SQL Server"/>

</
LinearLayout>

Step 4: Create a java file in your android’s project with name ConnectionClass.java and edit it as below:

package com.qtsdigital.dbconnect;

import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionClass {
   
// Change below settings as per your database ip and credentials
   
String ip = "98.143.147.250"; // if you have to add port then it would be like .i.e. 182.50.133.109:1433
   
String db = "DemoDb"; //Name of Database
   
String un = "DemoTable"; //Database user
   
String password = "$H6c5cs5"; //Database Password
   
@SuppressLint("NewApi")
   
public Connection CONN()
    {
       
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
       
StrictMode.setThreadPolicy(policy);
       
Connection conn = null;
       
String ConnURL = null;
       
try {
           
Class.forName("net.sourceforge.jtds.jdbc.Driver");
            ConnURL =
"jdbc:jtds:sqlserver://" + ip + ";" + "databaseName=" + db + ";user=" + un + ";password=" + password + ";";
            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;
    }
}

 

This class have all the information of IP Address, Database Name, UserName and Password and it will return a database connection object which can be used to connect with our database.

Step 5: Now create a MainActivity Class and edit it as below:

package com.qtsdigital.dbconnect;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.sql.Connection;
public class MainActivity extends AppCompatActivity {
   
Button btnConnect;
   
private ConnectionClass connectionClass; //Connection Class Variable
   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(
R.layout.activity_main);
       
btnConnect=findViewById(R.id.DBConnect);

       
btnConnect.setOnClickListener(new View.OnClickListener() {
           
@Override
           
public void onClick(View view) {
               
connectionClass=new ConnectionClass();
               
Connection conn = connectionClass.CONN(); //Connection Object
               
if (conn == null) {
                   
Toast.makeText(MainActivity.this, "Database Connection Failed!!!", Toast.LENGTH_SHORT).show();
                }
               
else{
                   
Toast.makeText(MainActivity.this, "Database Connection Established.", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

 

This MainActivity Class is the main file of this App.

Now run the project and Click on Button and see the result.

Hope you like this tutorial too.

Comments