Android Application Connect With MS SQL Server Step By Step Guideline For Begineer

First, download the JTDS driver for your OS. And Follow Next Step.

  1. Right click on app > New > Module.
  2. A window will open where you can find jar files when you scroll down.
  3. Select the widget another window will open, find the location of your jar and select.
  4. Finish. That is it you can start creating projects with SQL server after the build is finished.
  5. Now after adding JTDS you have to Add This Line In Your App Gradle File
dependencies{ implementation project(‘:jtds-1.3.1’)}

Check Your jtds Downloaded Version With Downloaded Version And Check With Dependencies Text here My Current Version 1.3.1 So I Add Here 1.3.1 If Your Version Another change This

Now we are Add Internet Permission To Manifest File

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mssql">
    // For Internet Connection Use Below Line
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <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>

Now we are going to make Connection Class.

Create A Java Class In Android Studio And Remember That Is The Main Database Controling Class For Ms Sql Server Connection And Another Work With Sql Server Releated .


package com.example.sample.myapplication;
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import android.os.StrictMode;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionClass {

    // Your IP address must be static otherwise this will not work. You //can get your Ip address
//From <em>Network and security in Windows.</em>
    String ip = "192.168.10.101";
    // This is default if you are using JTDS driver.
    String classs = "net.sourceforge.jtds.jdbc.Driver";
    // Name Of your database.
    String db = "NEWFIZTEST";
    // Userame and password are required for security.
   // so Go to sql server and add username and password for your database.
    String un = "sa";
    String password = "fizsa7,";

    @SuppressLint("NewApi")
    public Connection CONN() {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection conn = null;
        String ConnURL;
        try {
            Class.forName(classs);
            ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
                    + "databaseName=" + db + ";user=" + un + ";password="
                    + password + ";";
            conn = DriverManager.getConnection(ConnURL);
        }
        catch (SQLException se)
        {
            Log.e("safiya", se.getMessage());
        }
        catch (ClassNotFoundException e) {
        }
        catch (Exception e) {
            Log.e("error", e.getMessage());
        }
        return conn;
    }
}

You can now use connection class object to make connection with your database and perform queries on your table.

If this code not working for you then may be:

  1. You are using the wrong ipv4 address. You always have to use a static IP or this will not work!
  2. check your username and password.
  3. Check your query column name and table column names.
  4. check internet connection in your phone.
  5. Run this on real Device. This does not work on the emulator.

Still not working post your query as a comment I will solve it as soon as possible.

Thanks! Don’t forget to Like!!

Tips:

  1. Always keep your connection class separate. So that if you change your server address, you just need to modify one file.
  2. Whenever you are using a SQL query. Do not run it on main thread otherwise, you will get errors like:  Main Thread id having load skipped 144 thread.
  3. You can Async Task to run your query on the background while the screen shows Loading or progress dialog.
  4. You can also use Runnable and threads to move the execution of SQL query from the main UI thread to Created thread.
  5. Use Logcat To display errors you face during your execution.
  6. Create a package for all the different purpose java classes.

How To Check Ms sql Connection In Android

Suppose We Have An Activity In This Activity Have A TextView . We Find The TextView And Set Text That Is Connection Successfull TextView Text Is “Connected” Of Not Connected

  1. Create A Variable Of Connection Classs .
  2. Create Object Of Connection Class
  3. Check Connection Of Connection Class
package com.example.sample.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import java.sql.Connection;

public class MainActivity extends AppCompatActivity {
    ConnectionClass connectionClass;
    private  String z;
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView)findViewById(R.id.textView);
        connectionClass = new ConnectionClass();
      try {
          Connection con = connectionClass.CONN();
          if (con == null) {
              z = "Check Your Internet Connection";
              Toast.makeText(getApplicationContext(),z,Toast.LENGTH_LONG).show();
              textView.setText("not connected");
          }

          else {
              Toast.makeText(getApplicationContext(),"Connected",Toast.LENGTH_LONG).show();
              textView.setText("connected");

          }
      }

      catch (Exception e){}

    }
}

Summary Of Make Connection

  1. Create A Connection Class .
  2. Add Database jdts Driver.
  3. Add This Line In Your App Gradle File implementation project(‘:jtds-1.2.7’)
  4. Create Database Object And Check By This Way
  5. Add Internet Permission On Manifest File . <uses-permission android:name=”android.permission.INTERNET” />
ConnectionClass connectionClass;
connectionClass = new ConnectionClass();
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Check Your Internet Connection";
Toast.makeText(getApplicationContext(),z,Toast.LENGTH_LONG).show();
textView.setText("not connected");
}

else {
Toast.makeText(getApplicationContext(),"Connected",Toast.LENGTH_LONG).show();
textView.setText("connected");

}
}

catch (Exception e){}

Published by

Unknown's avatar

Nusrat Faria

I Am A Web Developer And A Android Developer. This Is My Personal Blog So Noted My Work For Helping People .

One thought on “Android Application Connect With MS SQL Server Step By Step Guideline For Begineer”

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.