• Michael

    Hello.

    I’m trying to connect my app with a database in a server in another computer through internet. I used your code but I have this error:
    7809-7809/com.example.michael.mysqlapp2 E/ERRO﹕ Network error IOException: failed to connect to /155.xxx.xxx.xxx (port 1433): connect failed: ECONNREFUSED (Connection refused)

    Any help?

    I have added the as well.

    • Hi Michael, I have tried this code from my device and also with the emulator to connect with a database which is in another computer and it worked.
      It is possible that there’s an error in your SQL configuration and that’s why you may be getting this error of “CONNECTION REFUSED”

      • Michael

        Hello Hitesh and thank you for such a quick responce.

        The computer you are talking about was in the same network with your device or did you connect through the internet?

        If it is the second case, do you have any thoughts about what configuration I might have to change in the SQL database/server?

        Thanks again so much for the quick responce!

        • I had tested this code in both situations.
          First case in same WiFi network : You have to give the IPv4 address of your computer in which your database in stored. And in the second case if your database is present in the internet you will have to give the Server name not the IP address to connect.
          In same network situation,to check whether the SQL server accept the IP address, connect it by putting the IP address itself, if it accepts the app will also connect
          and in second one try to connect SQL server by supplying the server name
          (workstation id=****.mssql.****.***;) if it connects the app will also connect.

          • Michael

            OK Hitesh, thank you again for your time!

            I will try these!
            Excellect article, keep up the good work!

  • Michael

    Hello again!

    If I want to connect with a remote MySQL database, what do I have to change in the code?

    • admin70

      This code is about sql connection not MySql..Sorry but I have no idea about MySql

    • Na0z

      put your localhost in “ConnectionURL”

  • This post is about SQL server connection…I have no idea about MySQL Database connection

  • JohnColtrane

    Hitesh:

    I enjoyed your article however I’m experiencing an issue when attempting to connect to the SQL server. My error is:

    Unknown server host name ‘Unable to resolve host “servername”: No address associated with hostname

    I’m attempting to connect from an emulator on my laptop to a SQL box within the same network. For the server name I have tried both the IP address and the server name – no success. I have added the following entries to the manifest file:

    Here’s the connection string:

    jdbc:jtds:sqlserver://servername;databaseName=TEST;user=username;password=password;
    Do you have any insight into this error? I can connect directly to the SQL box using the server name and password/user name, so it’s correct. Is there something that I’m missing?
    John
    John

  • What network are you using John? Is the database and device in same Wi-Fi network or you are using Internet and database is present on server (internet). I used to get this error when I entered the server name like (HITESH-PCSQLSERVER) but by entering IP address the error is resolved.

    • JohnColtrane

      Hitesh:

      Thanks for the response, but I have resolved my issue. We are correct I need to use the IP address in the connection string in addition to the port number and database name. Here’s the format that worked for me:

      jdbc:jtds:sqlserver://”+ adresseip +”:1433/lear_db;user=youruser;password=yourpass
      John.

  • If you are using WI-Fi network and database is also in the same network, then you must enter the IP address of your PC in which database is present.

  • JohnColtrane

    Hitesh:
    Great articles, I have successfully completed both. However, I have a question about security. Is using the JDBC drivers the best and most secure manner to connect android to SQL?
    John.
    John.

    • admin70

      No not at all, this article is just for knowledge purpose. If you are making an app for your client who will be using it for his/her company or personal purposes then its the best way. But if you are going to publish on playstore with your own app , its not a good idea of passing your Server name with username and password as someday someone could just decompile the app and get access to your full database. Thanks for your interest in my work. Cheers.

  • Luis Ontiveros

    Hitesh, in the code:

    } catch (Exception e) {
    Log.e(“ERRO”, e.getMessage());
    }
    return connection;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    I get in the word: “login” in red color with the following options :
    – Create layout resource file ‘login.xml’
    – Create layout value resource ‘login’
    – Create field ‘login’
    – Rename reference

    What should I do ?

    Thank’s.

    • Luis Ontiveros

      This I resolve the above code ok.

      But in this other code:

      @Override
      public void onClick(View v) {
      try {
      st = connect.createStatement();
      ResultSet rs = st.executeQuery(“select * from login where userid='” + edname.getText().toString() + “‘ and password='” + edpassword.getText().toString() + “‘”);
      if (rs != null && rs.next()) {
      Intent i = new Intent(Login.this, MainActivity.class);
      startActivity(i);
      } else {
      errorlbl.setText(“Sorry, wrong credentials!!!”);
      }

      I get an Error in the word “Login”: Cannot resolve symbol ‘Login’.

      How can I get ride of that Error ?

      Thanks a lot.

      • Na0z

        Change “Login.this.” for :

        Intent i = new Intent(getApplicationContext(), MainActivity.class);

    • Na0z

      try Clean Project, and Build Project.

  • Have you made login.xml file in the res>layout folder?????

    • Luis Ontiveros

      Thanks a lot., Creating the file solve my problem.
      Now I got all your code without errors.

      But wher I run the code, I got no response when I hit the LOGIN button.

      And I try to debug the code but didn’t enter to the Method: “public void onClick(View v)” in the Java Class: “Login.java”.

      I change the ipaddress, db, username and password, and try to connect from muy PC in a wired Network on my Work to Another PC (with SQL Server).
      And changed the Database, Table and the line with the “select” by another select, only to return data from the Database, like this:
      ResultSet rs = connect.createStatement().executeQuery(“select * from MT_Cat_Doctores where MT_Num_Doctor=’12345′”);

      The ipaddress I have to use is the one of the PC with SQL Server ? or I have to use de ipaddress of the Server where the databases are stored ?

      Thank You Hitesh.

      • Luis you have to use IP address of the PC where your database is stored

  • Mj Elle ♣

    good morning. I get an error under my login.java. it says error: class, interface or enum expected.
    what does it mean? please help! 🙁

  • Mj Elle ♣

    I also get a red font on MainActivity.class and when I hover the mouse to it, it says ‘cannot resolve symbol Main Activity’. how can I resolve this?

    • Have you made MainActivity.java file in your project, I have not mentioned it here as it will be made automatically when creating the project by Android Studio itself.

  • Mj Elle ♣

    Good morning, Sir. I was already able to launch the program but every time I tap/click the Login button, the app stops working and I always get redirected to the home screen of the device. Is there any way I can fix this? Your help will be very much appreciated. Thank you.

    • Hey I included download link for the application. See in the post.

      • Mj Elle ♣

        Same thing happens, Sir. I downloaded your app and had it run on android studio but every time it tries to connect to the database, the program stops working. Could the hardware be a factor here?

    • Can you say what’s the logcat output you are getting

      • Mj Elle ♣

        java.lang.NullPointerException
        at com.android.ddmlib.Client.sendAndConsume(Client.java:673)
        at com.android.ddmlib.HandleHello.sendHELO(HandleHello.java:195)
        at com.android.ddmlib.HandleHello.sendHelloCommands(HandleHello.java:66)
        at com.android.ddmlib.Client.getJdwpPacket(Client.java:772)
        at com.android.ddmlib.MonitorThread.processClientActivity(MonitorThread.java:317)
        at com.android.ddmlib.MonitorThread.run(MonitorThread.java:263)

        ddms: null
        java.lang.NullPointerException
        at com.android.ddmlib.Client.sendAndConsume(Client.java:673)
        at com.android.ddmlib.HandleHello.sendHELO(HandleHello.java:195)
        at com.android.ddmlib.HandleHello.sendHelloCommands(HandleHello.java:66)
        at com.android.ddmlib.Client.getJdwpPacket(Client.java:772)
        at com.android.ddmlib.MonitorThread.processClientActivity(MonitorThread.java:317)
        at com.android.ddmlib.MonitorThread.run(MonitorThread.java:263)

  • Are you using Emulator to test the application???

    • Mj Elle ♣

      Yes. Android Studio’s emulator.

    • Mj Elle ♣

      06-13 08:51:24.745 2289-2289/app.mysqlapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
      Process: app.mysqlapp, PID: 2289
      java.lang.NullPointerException: Attempt to invoke interface method ‘java.sql.Statement java.sql.Connection.createStatement()’ on a null object reference
      at app.mysqlapp.Login$1.onClick(Login.java:80)
      at android.view.View.performClick(View.java:4780)
      at android.view.View$PerformClick.run(View.java:19866)
      at android.os.Handler.handleCallback(Handler.java:739)
      at android.os.Handler.dispatchMessage(Handler.java:95)
      at android.os.Looper.loop(Looper.java:135)
      at android.app.ActivityThread.main(ActivityThread.java:5257)
      at java.lang.reflect.Method.invoke(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:372)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

      • I can’t really figure out whats wrong. It seems that may be your SQL server is having a problem or something else. I would suggest clean your project. It sometimes does the trick. Are you using the project from the download link above??

        • Mj Elle ♣

          Yes, everything. I didn’t change anything from the code except the server information and my credentials. I’m sad now. Anyway, thanks for always answering, Sir. God bless you.

          • connect = ConnectionHelper(username, password, db, ipaddress);
            This will be inside the try catch block of the button click listener, see the code I changed it.

      • محمد نجيب

        Please, Did you find a solution for this problem?
        I had same problem and I did not find any solution.

  • Lakshmi Narayanan Balasubraman

    million likes…. its simply working superb…. only need to config port number with the local ip….

    my server ip is 192.168.1.4

    port number is 1550

    so address will be
    192.168.1.4:1550

    Hitesh Vikani Sir… Good Job… Great Job… welcome sir….

    B.Lakshmi Narayanan
    9940292099
    Tuticorin

    • Thank you Lakshmi..but one request don’t call me Sir. I don’t wanna be sir to anyone 🙂

      • Lakshmi Narayanan Balasubraman

        ok Hitesh…. you awesome… now need to show values in grid and print the same :)….

    • shunny

      can u share ur whole code with us please……….. and kindly tell us which software u r using for android development and which server u r using thanks a bundle of thanks id u can mail ur code 🙂 nice.pari0004@gmail.com

  • Pingback: Android Listview from MS SQL server • ParallelCodes()

  • Pingback: Connect Android to MS SQL Database. • ParallelCodes()

  • Stevanus Nurkusuma Giri

    Hi, I got the same problem with miss Mj. I’m using eclipse and genny motion emulator. Any idea? Thx

    • connect = ConnectionHelper(username, password, db, ipaddress);
      This will be inside the try catch block of the button click listener, see the code, I changed it.

      • Stevanus Nurkusuma Giri

        Hi thx for the reply. Already try that but still same..
        And i already download with your code and do exactly same but the error still same. I think maybe from the MS SQL server? Can i see your configuration from your sql server configuration manager?

        • Hey does your SQL server gets connected using the IPv4 address on your computer or laptop. If yes, your SQL server is just fine. Additionally if you are using the database stored on the server on the internet, try to connect SQL server by supplying the server name (workstation id=****.mssql.****.***;) if it connects the app will also connect.

          • Stevanus Nurkusuma Giri

            Yes, my SQL server already connected using IPv4 and already same with my pc. I already try with the java code to get the data from database. And it can get the whole data from it. But when i’m trying with the android its failed. I haven’t using the internet one but maybe soon after get this working.
            I don’t have idea, i’m already trying another project that u r making. The list view one that shows the country. But somehow it shows the same error with this one.
            And I already try using another library JDBC but it also shows the same error. Do u have another way? Thx

          • admin70

            what is the error ur getting exactly? The code in the download link is different as it does not have the connect statement for button click listener, I later changed the code. The current program is right.

          • Stevanus Nurkusuma Giri

            I already know. The issue is because i haven’t check the library box for jtds inside the build path. Then clean the project. Thx

  • Stevanus Nurkusuma Giri

    Hi I’m changing a little bit the code from CountryList.java. And this one working. Hope this can help some people that have same problem with me

    package com.example.temp;

    import java.sql.Connection;

    import java.sql.DriverManager;

    import java.sql.ResultSet;

    import java.sql.SQLException;

    import java.sql.Statement;

    import java.util.ArrayList;

    import java.util.HashMap;

    import java.util.List;

    import java.util.Map;

    import android.annotation.SuppressLint;

    import android.app.Activity;

    import android.os.Bundle;

    import android.os.StrictMode;

    import android.util.Log;

    import android.view.View;

    import android.view.View.OnClickListener;

    import android.widget.Button;

    import android.widget.ListView;

    import android.widget.SimpleAdapter;

    import android.widget.Toast;

    public class CountryList extends Activity {

    Button Btn;

    ListView lstcountry;

    SimpleAdapter ADAhere;

    ConnectionClass connectionclass;

    String call, db, un, passwords;

    Connection connect;

    ResultSet rs;

    @SuppressLint(“NewApi”)

    private Connection CONN(String _user, String _pass, String _DB, String _server ) {

    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://” + _server + “;” + “databaseName=” + _DB + “;user=” + _user + “;password=” + _pass + “;”;

    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;

    }

    public void QuerySQL(String SQL) {

    try {

    Statement statement = connect.createStatement();

    rs = statement.executeQuery(SQL);

    List<Map> data = null;

    data = new ArrayList<Map>();

    while(rs.next()) {

    Map datanum = new HashMap();

    datanum.put(“A”, rs.getString(“CountryName”));

    data.add(datanum);

    }

    String[] from = {“A”};

    int[] views = {R.id.lblcountryname};

    ADAhere = new SimpleAdapter(this, data, R.layout.listtemplate, from, views);

    lstcountry.setAdapter(ADAhere);

    } catch (Exception e) {

    Toast.makeText(CountryList.this, e.getMessage().toString(),Toast.LENGTH_LONG).show();

    }

    }

    @Override

    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.countrylist);

    lstcountry = (ListView) findViewById(R.id.lstcountry);

    Btn = (Button) findViewById(R.id.btnview);

    connectionclass = new ConnectionClass();

    call = connectionclass.getip();

    un = connectionclass.getun();

    passwords = connectionclass.getpassword();

    db = connectionclass.getdb();

    connect = CONN(un, passwords, db, call);

    Btn.setOnClickListener(new OnClickListener() {

    @Override

    public void onClick(View v) {

    // TODO Auto-generated method stub

    QuerySQL(“SELECT TOP 10 * FROM countries”);

    }

    });

    }

    }

  • I get an “java.lang.NullPointerException: Attempt to invoke interface method ‘java.sql.Statement java.sql.Connection.createStatement()’ on a null object reference” Error…

    What can i do??

    TIA!

    • Hi Rick, this error may occur when you do not have jar lib included in your project. And if you are using eclipse, do include the jar lib in build path.

      • I use Android Studio. And i have jtds-1.3.1.jar included.

  • William Cook

    Here is my connection string
    “Data Source=tcp:s10.winhost.com;Initial Catalog=DB_xxxxxxx_testdb;User ID=DB_xxxxxxx_testdb_user;Password=******;Integrated Security=False;”

    As you can see I’m not using my local machine for sql server, since I don’t know the IP address of the database server can I use the data source?

    • It will work only put your data source name instead of ip address. I’m using it for my client application to connect to their database in my application like below in connectionclass :
      ip = “tcp:s10.winhost.com”;
      classs = “net.sourceforge.jtds.jdbc.Driver”;
      db = “database name”;
      un = “your username”;
      password = “your password;

    • William Cook

      It’s working now, thank you so much for your time.

      • Simon Mwai

        Hi william, what worked please specify

        • William Cook

          I first had my connection string built like:

          Data Source = “tcp:s10.winhost.com”;
          classs = “net.sourceforge.jtds.jdbc.Driver”;
          db = “database name”;
          un = “your username”;
          password = “your password;

          I changed it to:

          ip = “tcp:s10.winhost.com”;
          classs = “net.sourceforge.jtds.jdbc.Driver”;
          db = “database name”;
          un = “your username”;
          password = “your password;

          So I just changed “Data Source to “IP”

          That’s all I changed

          • Simon Mwai

            thanks. I will try

          • Hey Simon this is Hitesh. My computer got crashed and it took me a whole day to figure out what next to do. Sorry for late respond. I would like to say to you that the solution that I posted on this post took me more than a month to find a way to connect to MS SQL SERVER. It wasn’t easy anyways. And this solution works for me everytime.

          • Simon Mwai

            sorry for the crash. its a challenge we have to take

          • Mahmoud Gamil

            can u help me …

          • Mahmoud Gamil

            i can’t connect with sql . .. . .
            errors{
            Error:warning: Ignoring InnerClasses attribute for an anonymous inner class
            Error:(net.sourceforge.jtds.jdbc.CharsetInfo$1) that doesn’t come with an
            Error:associated EnclosingMethod attribute. This class was probably produced by a 🙁

          • Abhishek Jha

            Hey William Cook,
            I’m having issue in Connecting my android application with MS SQL Server at MyWindowsHosting.com
            please help me solve this
            i’m not getting what to do

          • Shibin Kalliatt

            please send me th complete code to mytapy@gmail.com

    • yousef

      where is datasource in my web host?

    • Ling

      Hi William, may i know by using connection string, what is the username for the db? is it the user id?

    • Athini Bashe

      does your app connect to the database using mobile data? or it can only connect through wifi ?

      • It can be used both ways depending where you store your database.

  • Pingback: Android JSON Parsing • ParallelCodes()

  • William Cook

    Thank you for responding, here is my code, can you help me get it to work
    public class MainActivity extends Activity
    {

    Connection connect;
    PreparedStatement preparedStatement;
    Statement st;
    String ipaddress, db, username, password;

    @SuppressLint(“NewApi”)
    private Connection ConnectionHelper(String user, String password,
    String database, String server) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
    .permitAll().build();
    StrictMode.setThreadPolicy(policy);
    Connection connection = null;
    String ConnectionURL = null;
    try {
    Class.forName(“net.sourceforge.jtds.jdbc.Driver”);
    ConnectionURL = “jdbc:jtds:sqlserver://” + server + “;”
    + “databaseName=” + database + “;user=” + user
    + “;password=” + password + “;”;
    connection = DriverManager.getConnection(ConnectionURL);
    } 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 connection;
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    TextView errorlbl = (TextView) findViewById(R.id.lblMsg);

    ipaddress = “tcp:s10.winhost.com”;
    db = “DB_xxxxxx_testdb”;
    username = “DB_xxxxxx_testdb_user”;
    password = “xxxxxx”;
    connect = ConnectionHelper(username, password, db, ipaddress);

    /*
    // loginbtn.setOnClickListener(new View.OnClickListener() {

    //@Override
    //public void onClick(View v) {
    */

    try {

    connect = ConnectionHelper(username, password, db, ipaddress);

    st = connect.createStatement();
    ResultSet rs = st.executeQuery(“select * from UserInfo”);
    if (rs != null && rs.next()) {
    //Intent i = new Intent(Login.this, MainActivity.class);
    //startActivity(i);
    errorlbl.setText(“Good connection”);
    } else {
    errorlbl.setText(“Sorry, wrong credentials!!!”);
    }

    } catch (SQLException e) {
    errorlbl.setText(e.getMessage().toString());
    }

    }

    }

  • Pingback: Android Game Tutorial • ParallelCodes()

  • YJ

    Intent i = new Intent(Login.this, MainActivity.class);

    “MainActivity” is not recognize on my Android Studio, any idea all expert? 😉

    YJ.

  • Arun K Nair

    Hi,
    I am getting the following error:

    “E/ERRO﹕ Network error IOException: socket failed: EACCES (Permission denied)”

    I have added the following permissions also:

    I am using Android studio 1.3. I turned of firewall, but no luck…

    DB is hosted in cloud.

    Following is the error log:

    08-09 19:15:28.884 5343-5343/? I/art﹕ Not late-enabling -Xcheck:jni (already on)
    08-09 19:15:29.148 5343-5355/com.android.test.test I/art﹕ Background sticky concurrent mark sweep GC freed 1604(94KB) AllocSpace objects, 0(0B) LOS objects, 9% free, 548KB/605KB, paused 2.435ms total 169.394ms
    08-09 19:15:29.156 5343-5355/com.android.test.test W/art﹕ Suspending all threads took: 8.113ms
    08-09 19:15:29.277 5343-5355/com.android.test.test I/art﹕ Background partial concurrent mark sweep GC freed 357(65KB) AllocSpace objects, 0(0B) LOS objects, 51% free, 487KB/999KB, paused 34.726ms total 53.304ms
    08-09 19:15:29.340 5343-5355/com.android.test.test W/art﹕ Suspending all threads took: 62.766ms
    08-09 19:15:29.381 5343-5343/com.android.test.test E/Errr….﹕ before Helper Oncreate
    08-09 19:15:29.382 5343-5343/com.android.test.test E/Err,,,﹕ Inside try,,,,
    08-09 19:15:29.388 5343-5343/com.android.test.test E/Err…﹕ after url
    08-09 19:15:29.421 5343-5355/com.android.test.test I/art﹕ Background sticky concurrent mark sweep GC freed 2822(252KB) AllocSpace objects, 1(14KB) LOS objects, 0% free, 1279KB/1279KB, paused 5.808ms total 35.429ms
    08-09 19:15:29.428 5343-5355/com.android.test.test W/art﹕ Suspending all threads took: 6.214ms
    08-09 19:15:29.516 5343-5350/com.android.test.test W/art﹕ Suspending all threads took: 11.041ms
    08-09 19:15:29.522 5343-5343/com.android.test.test E/ERRO﹕ Network error IOException: socket failed: EACCES (Permission denied)
    08-09 19:15:29.570 5343-5355/com.android.test.test I/art﹕ Background sticky concurrent mark sweep GC freed 4078(174KB) AllocSpace objects, 2(45KB) LOS objects, 5% free, 1660KB/1761KB, paused 35.622ms total 84.015ms
    08-09 19:15:29.580 5343-5370/com.android.test.test D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true
    08-09 19:15:29.583 5343-5343/com.android.test.test D/﹕ HostConnection::get() New Host Connection established 0xb3fe9250, tid 5343
    08-09 19:15:29.592 5343-5343/com.android.test.test D/Atlas﹕ Validating map…
    08-09 19:15:29.673 5343-5370/com.android.test.test D/﹕ HostConnection::get() New Host Connection established 0xb3fe9580, tid 5370
    08-09 19:15:29.694 5343-5370/com.android.test.test I/OpenGLRenderer﹕ Initialized EGL, version 1.4
    08-09 19:15:29.775 5343-5370/com.android.test.test D/OpenGLRenderer﹕ Enabling debug mode 0
    08-09 19:15:29.801 5343-5370/com.android.test.test W/EGL_emulation﹕ eglSurfaceAttrib not implemented
    08-09 19:15:29.802 5343-5370/com.android.test.test W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xb3f9b360, error=EGL_SUCCESS
    08-09 19:15:47.751 5343-5350/com.android.test.test W/art﹕ Suspending all threads took: 5.207ms
    08-09 19:16:20.279 5343-5343/com.android.test.test E/Errr….﹕ before Helper Onclick
    08-09 19:16:20.279 5343-5343/com.android.test.test E/Err,,,﹕ Inside try,,,,
    08-09 19:16:20.279 5343-5343/com.android.test.test E/Err…﹕ after url
    08-09 19:16:20.280 5343-5343/com.android.test.test E/ERRO﹕ Network error IOException: socket failed: EACCES (Permission denied)
    08-09 19:16:20.282 5343-5343/com.android.test.test D/AndroidRuntime﹕ Shutting down VM
    08-09 19:16:20.282 5343-5343/com.android.test.test E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.android.test.test, PID: 5343
    java.lang.NullPointerException: Attempt to invoke interface method ‘java.sql.Statement java.sql.Connection.createStatement()’ on a null object reference
    at com.android.test.test.MainActivity$1.onClick(MainActivity.java:86)
    at android.view.View.performClick(View.java:4780)
    at android.view.View$PerformClick.run(View.java:19866)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
    08-09 19:16:23.329 5343-5343/? I/Process﹕ Sending signal. PID: 5343 SIG: 9

  • Pingback: Android Storing Images in MS SQL Server • ParallelCodes()

  • md ishtiyaque

    hello sir , i am fresher and i am using ur code for create a connection with my data base but i got an error this is unfortunately your app has stopped . what i can do plzzzzz

  • Dan Kevin Capuno

    hi Sir,

    i got this error.

    E/ERRO﹕ Network error IOException: failed to connect to BINITL003/172.16.2.221 (port 1433): connect failed: EHOSTUNREACH (No route to host)

    can you help me? thanks in advance sir

  • md ishtiyaque

    hello sir , i am new and i don’t know how to assign port no in android plzz reply

    • what port r u talking about…you have to allow connections on your PC’s firewall there you have to add port no.

  • md ishtiyaque

    hello sir, i am using your code and create an project this working on android studio avd but not working on mobile
    ip=”xxx.xxx.xxx.xxx:xxxx”;
    dbname=”zxxxx”;
    id=”xxxx”;
    pass=”jjj”;
    can u give me solution

    • Can u please post your full javacode

      • md ishtiyaque

        good morning here is my full java code please try to solve my problem ….

        public class MainActivity extends Activity {

        EditText userid,pass;
        TextView errorlbl;
        Button click,cancel;
        Connection connect;
        PreparedStatement preparedStatement;
        Statement st;
        String ip, db, username,password ;

        private Connection ConnectionHelper(String user, String password,
        String database, String ip)
        {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
        .permitAll().build();

        StrictMode.setThreadPolicy(policy);
        Connection connection = null;
        String ConnectionURL = null;

        try {
        Class.forName(“net.sourceforge.jtds.jdbc.Driver”);
        ConnectionURL = “jdbc:jtds:sqlserver://” + ip + “;”
        + “databaseName=” + database + “;user=” + user
        + “;password=” + password + “;” ;
        connection = DriverManager.getConnection(ConnectionURL);

        } catch (SQLException se) {
        Log.e(“ERRO”, se.getMessage());

        Toast.makeText(this,”error in sql “, Toast.LENGTH_LONG).show();
        } catch (ClassNotFoundException e) {
        Log.e(“ERRO”, e.getMessage());

        Toast.makeText(this,”error class not found”, Toast.LENGTH_LONG).show();
        } catch (Exception e) {
        Log.e(“ERRO”, e.getMessage());

        Toast.makeText(this,”normal exception”, Toast.LENGTH_LONG).show();
        }

        return connection;

        }

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

        userid = (EditText) findViewById(R.id.editText);
        pass = (EditText) findViewById(R.id.editText2);
        click = (Button) findViewById(R.id.button);
        errorlbl = (TextView) findViewById(R.id.textView);

        ip = “xxx.xxx.xxx.xxx:xxxx”;
        db = “xxxxxx”;
        username = “xxxxxx”;
        password = “xxxxxxx”;

        connect = ConnectionHelper(username, password, db, ip);

        }

        public void login(View v) {

        try {
        connect = ConnectionHelper(username, password, db, ip);
        st = connect.createStatement();
        ResultSet rs = st.executeQuery(“select * from member_login where loginid ='”
        + userid.getText().toString() + “‘ and password ='”
        + pass.getText().toString() + “‘”);

        if (rs != null && rs.next()) {
        Intent i = new Intent(getApplicationContext(), Alps.class);
        startActivity(i);
        Toast.makeText(this,”connection successfull”, Toast.LENGTH_LONG).show();
        } else {
        errorlbl.setText(“User Id or Password Wrong!!!”);
        }
        } catch (SQLException e) {
        errorlbl.setText(e.getMessage().toString());
        Toast.makeText(this,”Sql error in login”, Toast.LENGTH_LONG).show();
        }

        }
        public void cancel(View view)
        {
        finish();
        }
        }

      • md ishtiyaque

        and I am Using JtDS 1.3.1 dist

  • Servesh Tiwari

    i want to do registration (name, age, username, password) and then login(username and password) and want to connect it with mssql database. Please help me as it is very urgent.
    If possible kindly mail me the solution.
    s.tiwari2494@gmail.com

  • Mohammed Najeeb

    Dear sir
    When I ran your application , I had this error
    09-20 03:27:30.300 11744-11744/app.mysqlapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: app.mysqlapp, PID: 11744

    java.lang.NullPointerException: Attempt to invoke interface method
    ‘java.sql.Statement java.sql.Connection.createStatement()’ on a null
    object reference
    at app.mysqlapp.Login$1.onClick(Login.java:80)
    at android.view.View.performClick(View.java:4780)
    at android.view.View$PerformClick.run(View.java:19866)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

    Can you please tell me what is the problem?

  • Pingback: Why i can not to connect sql server with android? [duplicate] - BlogoSfera()

  • Pingback: How to fill Data in Android Spinner using MS SQL Database • ParallelCodes()

  • Mubasshir Wangde

    what is addproducts its giving me error that cannot resolve the symbol Addproducts

      • Mubasshir Wangde

        do i need to write the whole code as by only creating the java file the errors are gone but while running the app its showing cannot connect to sql server

        • Mubasshir Wangde

          sorry … i just need to knw that how to connect to the sql server as only ip address is not doing the job

          • Does your SQL gets connected only using the IP address on PC??

          • Mubasshir Wangde

            its not getting connected only shwing error in sql connection and i m using the app on my phone which is working on wifi and the sql server is on pc

      • Mubasshir Wangde

        can u tell me how to get the data source name

  • Mubasshir Wangde

    hitesh ,i m using the app on mobile which is working on wifi connection and my sql database is on Pc …so please can u give me the idea of how to connect it..

    • Please refer http://www.parallelcodes.com/sql-configuration/ for configuring your SQL

      and https://msdn.microsoft.com/en-us/library/cc646023.aspx FOR Firewall config…hope this helps

      • Mubasshir Wangde

        thank u soo much for helping ….i want to ask u that is it possible to connect our sql database to the android application when the app is on wifi and the sql server is on the pc on some other connection means i have checked ur tutorial of calling json files n all … no need to do that na ….means no need of web services na to extract and insert the data?

  • jehad

    where is the link to download the application? I can’t find it.

  • YIMY JOSUE HERCULES RUBIO

    Hi, I follow the tutorial, but i have this error: DB server closed connection in the log, and in the App Toast says: Error in Connection whit SQL Server.

    Can you help me please?

    • may be your sql instance is stopped..please check..

      • sushma rani

        Please suggest what can i do.i am unable to connect
        Console message are
        Waiting for device.
        Target device: Nexus_4_API_23 [emulator-5554]
        Uploading file
        local path: C:UsersJAPAndroidStudioProjectsFTAppappbuildoutputsapkapp-debug.apk
        remote path: /data/local/tmp/com.example.jap.ftapp
        Installing com.example.jap.ftapp
        DEVICE SHELL COMMAND: pm install -r “/data/local/tmp/com.example.jap.ftapp”
        pkg: /data/local/tmp/com.example.jap.ftapp
        Success

        Launching application: com.example.jap.ftapp/com.example.jap.ftapp.MainActivity.
        DEVICE SHELL COMMAND: am start -D -n “com.example.jap.ftapp/com.example.jap.ftapp.MainActivity” -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
        Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.jap.ftapp/.MainActivity }

        Waiting for process: com.example.jap.ftapp
        Connected to the target VM, address: ‘localhost:8614’, transport: ‘socket’

        • Sorry but I’m unable to understand your Problem, but try this above the catch(Exception ex) block, write this :
          catch (SQLException ex)
          {
          isSuccess = false;
          z = ex.getMessage().toString();
          }
          I learnt this recently and this is helping me a lot. Hope this will work for you as well,
          Let me know what happens

          • sushma rani

            error throw in connection no establish error msg

            Error in connection with SQL server

          • Your sql server might not be configured.

          • Mr Kang

            i use plesk panal

            Error in connection with SQL server

        • Joe Kevin Rayan

          Hi! i had the same problem!

          conn = DriverManager.getConnection(“jdbc:jtds:sqlserver://192.168.1.100:1433/Andro;user=” + un + “;password=” + password);

          use this instead of this
          ConnURL = “jdbc:jtds:sqlserver://” + ip + “;”
          + “databaseName=” + db + “;user=” + un + “;password=”
          + password + “;”;

          and also delete these

          String ip = “192.168.1.100:1433”;
          String classs = “net.sourceforge.jtds.jdbc.Driver”;
          String db = “Andro”;

          because u r mentioning them in the Driver.getConnection itself u dont need to derive above

          also make sure to add

          Class.forName(“net.sourceforge.jtds.jdbc.Driver”).newInstance();

          inside try above conn……

          here is the complete code of ConnectionClass.java

          package com.example.lenovo.androdb;

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

          public class ConnectionClass {

          String un = “sa”;
          String password = “sa123”;

          @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”).newInstance();
          /*ConnURL = “jdbc:jtds:sqlserver://” + ip + “;”
          + “databaseName=” + db + “;user=” + un + “;password=”
          + password + “;”;*/
          conn = DriverManager.getConnection(“jdbc:jtds:sqlserver://192.168.1.100:1433/Andro;user=” + un + “;password=” + password);
          } 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 worked fine for me! 🙂

  • Muslim Khan

    Hi sir can u plz tell me why you use package Hitesh.sqlapp?

  • Muslim Khan

    my application name is AlHumaidiGroupUAE so can I uuse package AlHumaidiGroupUAE.sqlapp?

  • shunny

    AOA bro
    i have a problem i want to connect my android application which is already connected with a web site for that i want to connect with this database which is created in sql server so plz help me about this if u can thanks alot

    • Yeah, use the server name instead of IP address it should get connected.

  • Mubasshir Wangde

    hi….. can u tell me how retrieve data from sql database and create a button? thanks in advance..:)

  • Muslim Khan

    Hi Hitesh Bhai I m using sql server database on my web server and I want to use same sql databse in m andoid application my data source is

    connectionString=”server=sql2502.shared-servers.com,1087;database=MYDB;Uid=user;Password=pwd”
    how can I connect to this Database Server

    • Hi bhaijaan…can u say me connectionString=”server=sql2502.shared-servers.com,1087;database=MYDB;Uid=user;Password=pwd” what is 1087 in this one.

      • Muslim Khan

        this one is port number of web server where database is running

        • see I dont know about port number as I do not need port number for my application. May be you should try deleting the port number in android.

          ip = “tcp:s10.winhost.com”;
          classs = “net.sourceforge.jtds.jdbc.Driver”;
          db = “database name”;
          un = “your username”;
          password = “your password;

          • Muslim Khan

            I have deleted the port number and I did without port number also but still not connecting its giving me this msg
            “failed to connect server”

  • Yemide

    @hiteshvikani:disqus can I engage you to develop an Android app for me?

    Thank you.

  • shashi patil

    buddy im using this code and it works fine!!! but the same thing when i use in next activity only change in query the doinbackgroung is not executing what is the problem???????

    • Hi shashi….may be there might be error in your query pls check

      • shashi patil

        hitesh… i want a dependent spinner… the 2nd spinner shud display the related data when i click on the 1st spinner….. im unable to achieve to do this from many days… solution is must please share the code …. thank you..

  • mahesh

    11-05 00:07:20.204: E/AndroidRuntime(892): FATAL EXCEPTION: AsyncTask #3
    11-05 00:07:20.204: E/AndroidRuntime(892): java.lang.RuntimeException: An error occured while executing doInBackground()
    11-05 00:07:20.204: E/AndroidRuntime(892): at android.os.AsyncTask$3.done(AsyncTask.java:299)
    11-05 00:07:20.204: E/AndroidRuntime(892): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
    11-05 00:07:20.204: E/AndroidRuntime(892): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
    11-05 00:07:20.204: E/AndroidRuntime(892): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
    11-05 00:07:20.204: E/AndroidRuntime(892): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
    11-05 00:07:20.204: E/AndroidRuntime(892): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
    11-05 00:07:20.204: E/AndroidRuntime(892): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
    11-05 00:07:20.204: E/AndroidRuntime(892): at java.lang.Thread.run(Thread.java:841)
    11-05 00:07:20.204: E/AndroidRuntime(892): Caused by: java.lang.VerifyError: net/sourceforge/jtds/jdbc/TdsCore
    11-05 00:07:20.204: E/AndroidRuntime(892): at net.sourceforge.jtds.jdbc.JtdsConnection.(JtdsConnection.java:359)
    11-05 00:07:20.204: E/AndroidRuntime(892): at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
    11-05 00:07:20.204: E/AndroidRuntime(892): at java.sql.DriverManager.getConnection(DriverManager.java:179)
    11-05 00:07:20.204: E/AndroidRuntime(892): at java.sql.DriverManager.getConnection(DriverManager.java:144)
    11-05 00:07:20.204: E/AndroidRuntime(892): at com.example.zzzsqldb.ConnectionClass.CONN(ConnectionClass.java:34)
    11-05 00:07:20.204: E/AndroidRuntime(892): at com.example.zzzsqldb.MainActivity$DoLogin.doInBackground(MainActivity.java:72)
    11-05 00:07:20.204: E/AndroidRuntime(892): at com.example.zzzsqldb.MainActivity$DoLogin.doInBackground(MainActivity.java:1)
    11-05 00:07:20.204: E/AndroidRuntime(892): at android.os.AsyncTask$2.call(AsyncTask.java:287)
    11-05 00:07:20.204: E/AndroidRuntime(892): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
    11-05 00:07:20.204: E/AndroidRuntime(892): … 4 more

    • mahesh

      i dnt have idea about that..plz sole n thank you

      • Pls show me your code file

        • mahesh

          package com.example.zzzsqldb;

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

          import android.app.Activity;
          import android.content.Intent;
          import android.os.AsyncTask;
          import android.os.Bundle;
          import android.view.View;
          import android.widget.Button;
          import android.widget.EditText;
          import android.widget.ProgressBar;
          import android.widget.Toast;

          public class MainActivity extends Activity {

          ConnectionClass connectionClass;
          EditText edtuserid,edtpass;
          Button btnlogin;
          ProgressBar pbbar;
          @Override
          protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          connectionClass = new ConnectionClass();
          edtuserid = (EditText) findViewById(R.id.edtuserid11);
          edtpass = (EditText) findViewById(R.id.edtpass11);
          btnlogin = (Button) findViewById(R.id.btnlogin11);
          pbbar = (ProgressBar) findViewById(R.id.pbbar111);
          pbbar.setVisibility(View.GONE);
          btnlogin.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
          DoLogin doLogin = new DoLogin();
          doLogin.execute(“”);
          }
          });
          }
          public class DoLogin extends AsyncTask
          {
          String z = “”;
          Boolean isSuccess = false;
          String userid = edtuserid.getText().toString();
          String password = edtpass.getText().toString();
          @Override
          protected void onPreExecute() {
          pbbar.setVisibility(View.VISIBLE);
          }
          @Override
          protected void onPostExecute(String r) {
          pbbar.setVisibility(View.GONE);
          Toast.makeText(MainActivity.this,r,Toast.LENGTH_SHORT).show();
          if(isSuccess) {
          Intent i = new Intent(getApplicationContext(), AddProducts.class);
          startActivity(i);
          finish();
          }
          }

          protected String doInBackground(String… params) {
          if(userid.trim().equals(“”) || password.trim().equals(“”))

          z = “Please enter User Id and Password”;

          else
          {
          try {

          Connection con = connectionClass.CONN();

          if (con == null) {
          z = “Error in connection with SQL server”;
          } else {

          String query = “select * from AreaMaster where AreaName='” + userid + “‘ and AreaCode='” + password + “‘”;
          Statement stmt = con.createStatement();
          ResultSet rs = stmt.executeQuery(query);
          if(rs.next())
          {
          z = “Login successfull”;
          isSuccess=true;
          }
          else
          {
          z = “Invalid Credentials”;
          isSuccess = false;
          }
          }
          }
          catch (Exception ex)
          {
          isSuccess = false;
          z = “Exceptions”;
          }
          }
          return z;
          }
          }
          }

          • mahesh. are you using eclispe or Android Studio?? It is the error of integrating JTDS library in your app..pls see it.

          • mahesh

            i am using eclispe

          • Go to your project Properties > Java build Path > Order and Export and select all

          • mahesh

            i ditd. bt getting same error

          • mahesh

            hey. r u there

          • yes..I did the same and it worked for me

          • mahesh

            i did and its not working

          • mahesh

            hey…rpl plz

        • mahesh

          n this is my connection class

          package com.example.zzzsqldb;

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

          import android.annotation.SuppressLint;
          import android.os.StrictMode;
          import android.util.Log;

          public class ConnectionClass {

          String ip =”192.168.1.5/1433″;
          //String ip1=”169.254.145.79/1433″;
          // String ip2=”127.0.0.1/1433″;
          String classs = “net.sourceforge.jtds.jdbc.Driver”;
          String db = “online_billing”;
          String un = “xxx”;
          String password = “xxxxxxxxx”;
          // ConnectionHelper connect;
          @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(classs);
          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;
          }
          }

  • Alfred Paldez

    will this work on Rev23 SDK?

  • Alfred Paldez

    will this work on API23 SDK and for the API24?

  • Kuldeep

    Hi…Can you please help me..I just download your code and make same database. After that I run app in android studio…but it gives error..after putting user name & password application forcely closed…I do’nt understand what is the problem..?

  • bilgee

    Network error IOException: failed to connect to /192.168.1.118 (port 1433): connect failed: ECONNREFUSED (Connection refused)—–>>i have a local server in my laptop. my android device and laptop are connected same wifi. And wireless adapter ip address is 192.168.1.118. I cant connect mssql server. pls help!!! sorry for english. thank you

  • FrostyPinky

    I got an error “Unexpected Token” in this line –

    String classs = “net.sourceforge.jtds.jdbc.Driver”;

    what does it mean ? I already imported the jar file in library and also added it as a library

  • FrostyPinky

    Thanks is working now

  • Avrohom Singer

    Many thanks for this wonderful work.

    Compiling it with Android Studio gets the following two lint messages:

    message=”Invalid package reference in library; not included in Android: `javax.naming`. Referenced from `net.sourceforge.jtds.jdbcx.JtdsDataSource`.”
    .
    message=”Invalid package reference in library; not included in Android: `javax.transaction.xa`. Referenced from `net.sourceforge.jtds.jdbc.XASupport`.”

    Are those issues harmful?

    Is there any way to satisfy the lint / gradle compiler?

    PS. I am using the jtds-1.3.1 version.

  • Pingback: Android using Stored Procedure - MS SQL Server • ParallelCodes()

  • Mirce Novakovski

    Hello Hitesh, thanks for your answer, i have another one when i try to connect to sqlserver with instance ‘SQLSERVERInstancename’
    what should be the string ip ? jdbc:jtds:sqlserver://SQLSERVERInstancename;databaseName=Andro;user=test;password=test;

    • Hi Mirce, IP address is the IPv4 address of your computer if your database is stored in desktop PC and you are using Wifi network to connect with it.
      Or else, if the database is stored on internet server, you must be having the connectionString to connect so just replace the Ip address with the server address.

      • Mirce Novakovski

        Thanks Hitesh for your answer, i try with the ipv4 but its not connecting, the problem is the multiply instances on the server

        is my connection string ok? the string is jdbc:jtds:sqlserver://SQLSERVERInstancename;databaseName=Andro;user=test;password=te

        • yes its correct I think.
          db = “DB_NAME”;
          call = “SQL5018.myASP.NET”;
          un = “Username”;
          passwords = “********”;

      • M N

        Hello Hitesh,

        Thank you very much for your post and support. I connected to the DB successfully, definitely after fixing many issues, pretty much about SQLServer 2008 R2 configuration. I use ipconfig and get the IPv4 address since the DB is in my local laptop and I’m using wifi. I have another issue. I have to change the ip in the ConnectionClass all the time when my laptop is connected to other network. I think IPv4 is a ‘static ip address’ and I removed the TCP Dymanic Post number (In SQL Configuration Manager > SQL Server Network Configuration > Protocols for SQLExpress > TCP/IP > IPAll). Do you know how I can get rid of this issue? I should NOT change the ip address all the time when the laptop is connected to different network (at home, at work, at coffee shops)

        • I faced the same issue, so I made a activity with Username, password, DB name and its IP address textboxes so that I have not to change the details everytime in code itself.

  • ikram hussain

    Intent i = new Intent(MainActivity.this, AddProducts.class);

    error on AddProducts.class please help?

      • ikram hussain

        sir i try but its giving some other errors …sir actaully i got my university final project that work like MS SQL and so if you have that kind of stuff so please help me i would be very thankful to you

        • What error you are getting ikram?

          • ikram hussain

            sir is this code work with webservice or getting data directly ?

          • ganesan

            sir3

      • ikram hussain

        and even that kind of gui fragmented 🙁

    • ap

      cannot resolve symbol AddProducts for me.
      please help

  • Simon Mwai

    hi I have a problem getting the jdts library in the project. Kindly take me thru. am using Android studio 1.4

    • What problem ur getting?

      • Simon Mwai

        help me out sir, am stuck with this. I have imported the jtds jar file and now android is not building

        • How you added the jar files..have u just copied it, in your lib folder?
          After copying the jar file in the lib folder of your project.. also right click on the jar file and add it as library.

          • Simon Mwai

            hi .
            allow me to disturb u mr. Vikani. I think i found my way out. the build error is gone. This is wot i have in my project. please advise whether i got it ok.

          • Simon Mwai

            I hav another challenge with SQL server connection.
            the error from my phone is “ERROR IN CONNECTION WITH SQL SERVER”
            this is the error in the logcat

          • Simon Mwai

            This is my 5th day struggling with this 🙁
            kindly help me out

          • yes everything looks OK, so is your connection working now?

          • Simon Mwai

            I hav another challenge with SQL server connection.
            the error from my phone is “ERROR IN CONNECTION WITH SQL SERVER”

            I hav configured SQL server to allow remote access in a link you
            provided earier. My SQL server is on PC the phone is using its own
            internet and the PC is using a huawei USB modem. is there anything am
            missing in the whole setup?
            This is my 5th day struggling with this 🙁
            kindly help me out this is the error in the logcat

          • See the first thing is if your Database is on a local PC (like it’s in your case) you will have to be in same network (the PC is connected via lan cable or Wifi and also the mobile is connected in same network itself).
            Second if its on the cloud (internet like domain name), you will have a connectionString to connect with your DB (it’s a must). Then you will have to supply the server name instead of IP address over here.
            Let me know what happens Simon.

          • Simon Mwai

            am giving up. I hav been digging but there is no response the error still stand

          • Simon Mwai

            ……….Second if its on the cloud (internet like domain name), you will have a
            connectionString to connect with your DB (it’s a must). ……..
            kindly give me a sample of connection string to guide me with the string syntax

  • Simon Mwai

    hi I have a problem getting the jdts library in the project. Kindly take me thru. am using Android studio 1.4

  • Mansoor Rehman

    How to add the jar file in the project?

    • If you are using the Android Studio for your project, then you will have to copy the jar file (library file) in the lib folder and then add it as library.

  • shashi patil

    hitesh… i want a dependent spinner… the 2nd spinner shud display the related data when i click on the 1st spinner….. im unable to achieve to do this from many days… solution is must please share the code …. thank you..

    • Spinner using SQL or local SQLite database?

      • shashi patil

        no buddy using this concept only…..

        • shashi patil

          im waiting hitesh…. any solution???

          • SelectedIndex changed method will work for you.

          • shashi patil

            i did hitesh….. thanks for ur reply

          • shashi patil

            hitesh im facing another problem.. i want a listview with checkbox. i have successfully addede checkbox with listview but unable to fire the checkbox listener with same example…. will you help me????

          • shashi patil

            hitesh i have used multichoice property instead check box….. but the problem is im unable see the items of listview but when i click on listview the related item is showing on toast…… whats the issue…. please reply soon…..

      • shashi patil

        from sql server only…. im getting value in 1st spinner but unable to pass the selected item of spinner in second… which shud show related item from database….

  • Dominik

    Hi there, I have a problem. My app always tells me that there’s a connection error with my SQL Server. The classs is alwasys classs = “net.sourceforge.jtds.jdbc.Driver”; or do I have to change anything? because I don’t know where my error is coming from. Thanks a lot for helping me

    • Hi Dominik, looks like you have got the server name incorrect. Try removing the (http://) or (https://) from it

      • Dominik

        Thanks a lot for your answer but now I get this error again:
        E/ERRO: Network error IOException: failed to connect to mysqladmin.webclient4.de/136.243.32.136 (port 1433): connect failed: ECONNREFUSED (Connection refused)

        • is your database configured to allow remote connection?

          • Dominik

            if I enable remote access…Is the server as secure as before?

          • Yes it will be secured…just ensure that you don’t share your credentials

          • Dominik

            okay, what do I have to write into the servername field when I try to connect with my server. Because the Microsoft SQL always can’t find the server

          • this kind of error only appears when the sql is not configured.

          • Dominik

            But the SQL Server Network Configuration > Protocols for SQLEXPRESS says me that there is nothing to show, so what can I do?

  • Dharmesh Patel

    Hello Mr.Hitesh Please Help Me. To AutoComplete TextBox From Ms Sql Server Database

    Thanks In Advance

  • Simon Mwai

    thanks very much Mr.Vikan for your full time concerns. I have not been able to connect. I have taken a break. I have tried for two weeks now. i hav not given up thou. am in the process of getting my db on cloud so that i can reduce the hussels of this configurations. am working on a project and challanges are my sweet challenges. So Mr. Vikan i will get back to you soon

    Thanks for the new directives you added on this post. It will save many.

  • Dharmesh Patel

    Hello Mr. Hitesh Please Can You Give Me Example For AutoComplete Textbox In Android With Sql Server Database

    Thank In Advance

  • Simon Mwai

    hi Mr. Vikani. am configuring a database on the cloud server. my concern is the security of the data. Currently am connecting to the database directly with the connection string and no web service. is this safe and what other methods can i use. Am using ms sql 2008. thanks you

  • Melwin

    Hi Mr Vikani,,, I used your code and it worked like a charm it emulator.. but it doesn’t work in the phone… Every time i login or access i get a FATAL error.. from the phone… even the emulator uses the remote connection

    • Hi Melwin if the code is working on your emulator and not on your phone…please check the logcat output you might get fair idea why it’s not working…let me know

      • Melwin

        It said Connection timed out.. It a lot of time retrieving the data from the database, Hence had to change to REST Api.. But your technique was neat and good..

      • Melwin

        ya the problem was it needed very fast internet
        so later i changes it to async task to do on pre exccute() later it worked

  • Pingback: Android Login application using MS SQL Server and SharedPreferences • ParallelCodes()

  • yousef

    help please…. i build my app with sql database,my app run perfectlly on localhost but when i create sql database on my web host the app stop… ip address for my web host 90.153.255.245

  • Wachirapon Sompee

    I test the project by wifi is available but by mobile data network is doesn’t work. What’s wrong?

  • anil

    hey man , i have trouble….i cant connect the android to the sql server here below my code

    i just change database server name instead of ip….

    ConnectionConfig.java

    package com.umem.newdemo;

    import android.annotation.SuppressLint;
    import android.os.StrictMode;
    import android.util.Log;

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

    /**
    * Created by aNnY vIrUs on 1/11/2016.
    */
    public class ConnectionConfig {
    String ip = “ANNYVIRUS-PC”;
    String classs = “net.sourceforge.jtds.jdbc.Driver”;
    String db = “andro”;
    String un = “aNnYvIrUs-PC\aNnY vIrUs”;
    String 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(classs);
    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;
    }
    }

    mainactivity.java
    database code to connect
    try
    {
    String name = et_name.getText().toString();
    String pwd = et_pwd.getText().toString();

    Connection con = connect.CONN();
    if (con == null)
    {
    tv_errmsg.setText(“Error in connection with SQL server”); ///i am getting this error after executing on eulator.
    }
    else
    {
    String query = “insert into just values(‘”+name+”‘,'”+pwd+”‘)”;
    Statement stmt = con.createStatement();
    stmt.executeUpdate(query);
    tv_errmsg.setText(“Record Inserted successfully”);
    }
    }
    catch(Exception e)
    {
    tv_errmsg.setText(“record insertting fails…!”);
    }

  • Vivek K

    I’m a fresher in Software Development. I followed your code. How can I connect my device with my laptop, without having any static IP or Database hosting? I just need to retrieve the rows in SQL Server 2008 in my android phone. Please help..

  • Code Geek

    it returns, class not found exception. (net.sourceforge.jtds.jdbc.Driver) But i already import jtds library on my application. Somebody , help me with this.

    • The error means that you have not properly impoerted the library file.
      Please see

      • Code Geek

        I already fix this issue, I change my jar from 1.27 to 1.31. It works, maybe it has something to do with the library cause i imported my new library the way i imported the old one but it works. Thank you hitesh , your code help me a lot. Anyways, i modified the connection string for me to connect to a named instance. and It works .

        package freecs.allen.andro;
        import android.annotation.SuppressLint;
        import android.os.StrictMode;
        import android.util.Log;
        import java.sql.SQLException;
        import java.sql.Connection;
        import java.sql.DriverManager;

        /**
        * Created by Allen on 21-Jan-16.
        */
        public class ConnectionClass {
        String ip = “[IP of the Server]”;
        String classs = “net.sourceforge.jtds.jdbc.Driver”;
        String db = “[Database]”;
        String un = “[auth login]”;
        String password = “[auth password]”;
        String instance =”[instance name]”;
        @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(classs);
        ConnURL = “jdbc:jtds:sqlserver://” + ip + “;” + “instance=” + instance +”;”
        + “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;
        }}

  • kaivalya wankhede

    Hey Hitesh I am new here i am getting error “Error:(34, 27) error: cannot find symbol variable se”

    Hope you will give me solution quickly

  • kaivalya wankhede

    public class ConnectionClass {
    String ip = “192.168.50.125”;
    String classss = “net.sourceforge.jtds.jdbc.Driver”;
    String db = “Login_user”;
    String un = “KAIVALYA-PC\KAIVALYA”;
    String password = “”;

    HEY HITESH I AM GETTING PROBLEM WITH CONNECTING SQL AS I AM TRYING TO CONNECT LOCALLY SERVER PLEASE HELP

  • John

    Hi mate,

    DATA
    UserID: test
    password: 123456

    When i entered wrong password, the system show “Invalid Credentials”. It look everything correct here.

    But, when in entered correct password, the program will crashed and exit exceptionally without any reasons.

    Any comments?

    TQ

  • shashi patil

    hitesh i want update pswd in mysql using volley library… partially i achieved it but when false statement executes then also im getting message as pswd updated… only here im stuck will you correct it???

  • Hector Orozco

    Hello Hitesh good work! I followed your guide but I’m having connection issues whit my application!!! I can’t connect to the server and I don’t know why!! I’ve debbuged the class CONN() and I realize that the Conection conn; is still null after I set the ConURL. I checked my server data such ip Address, DB, Password, etc. And it is OK. I’m getting desperate at this point!!!

    • Can u post the code over here please!

      • Hector Orozco

        Look, the variable conn still null! but I checked several times the ip or Database or the password and they are correct!! it just get into the exception catch!

        • You will have to register your IP address on the server where your database is hosted. Also check if it’s accepting remote connections

        • Mark Heddison Bacsain

          Were you able to fix this Hector? I encountered the same problem. I’ll looking for possible solutions at the moment.

          • Hector Orozco

            Yes, It seems that I had problems with the ip Address, and some other people toldme to enable the SQL Browseer service on the server. With that I’ve solved my errors. Hope you can solve yours

  • Medi

    Hey, I am trying to access my local MS SQL and using am emulatorto test the app, I changed the ip to 10.0.2.2 instead of 127.0.0.1 since it point’s back to the emulator virtual machine, however I am unable to access the DB and read from the table. No error message just Connection timed out

    Any suggestion ?

  • Prasun Pandey

    Hi Hitesh,
    I am getting following Error. Please advise. Appreciate your work buddy. Please, help ASAP.
    E/ERRO: Network error IOException: failed to connect to /192.168.1.9 (port 1433): connect failed: ETIMEDOUT (Connection timed out)

    • Your Sql server is not configured I think

      • Prasun Pandey

        What i am missing here? How it need to be configured? I have enable TCP ports and listening fine.

  • Prasun Pandey

    Below is my connection.java file

    package ppras.sqlserver;

    import android.annotation.SuppressLint;

    import android.os.StrictMode;

    import android.util.Log;

    import java.sql.SQLException;

    import java.sql.Connection;

    import java.sql.DriverManager;

    /**

    * Created by H-PC on 16-Oct-15.

    */

    public class ConnectionClass {

    String ip = “10.0.2.2:8080”;

    String classs = “net.sourceforge.jtds.jdbc.Driver”;

    String db = “Andro”;

    String un = “sa”;

    String password = “HPE@12345”;

    @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(classs);

    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;

    }

    }

  • Athini Bashe

    Hi Hitesh

    i don’t know whether u’ll be able to assist me on this. i have created an amazon rds instance for MS sql server then logged in on ms sql server on my local machine using the rds instance credentials and created my database.

    now i can login to this database when using the wifi that my machine is connected to but i can’t login on the app using mobile data or any other wifi. The connection class is the same as yours but for IP i used the instance endpoint

    The app is timing out when using mobile data

    • Its absolutely not possible to do show. See when you are using the same Network to which your computer or your database source is connected everything will work fine. But if both are different network its possible. For this you will have to host your database on Internet.
      A connection median is necessary. When both are in same network your Wifi router or server act us a provider, but on different network there’s no such intermediate node, hence connection will time out, as the app is trying to connect, but there’s no one to listen to the app.

      • Athini Bashe

        makes sense, when it comes to databases that are not on the local machine i’m clueless. if u have any information on how to make my database accessible public through any type of internet connection that information would be valuable to me, i’ve been trying all types of databases

      • Athini Bashe

        currently this is what i have

      • Athini Bashe

        it’s working now. Thanks Hitesh

  • Handy Susanto

    why you using StrictMode in your ConnectionClass ?

  • Şule IŞIK

    this error is “Error in connection with SQL server”; .why ? I wrote my database information in my project.

  • haresh

    hi how to clear the error E/ERRO: Network error IOException: failed to connect to /192.168.1.100 (port 1433): connect failed: ECONNREFUSED (Connection refused)

  • Anukriti Lamaniya

    where is the addproducts.class in the project?

  • Gary Williams

    Hi finally got it working. Thanks heaps. One thing. Sorry haven’t read all the posts. Column names are now case sensitive. It should be “Password” not “password” in MainActivity.

    • Hound Hunter

      Hiii there i’ve follow above post regarding SQL connection with Android. I followed everything and write the code as it like above just one change which is ip address. Rest of the code and db data is same like above but when i run it it says “Error in connection with SQL server”. Please help you out. Waiting for your response

  • Robin Wirlan

    Hi all,

    I’ve created an Android application in Monodroid and connected to SQL Server to fetch the data from the tables created.Everything is working fine .

    Now , I’ve converted the same to APK format , put the same into my android phone , installed the application in my mobile . Now , I need to access my sql server .

    Please tell me the procedure , How i can connect to my sql server in the LAN with my Android Mobile.

  • m khurram ilyas

    the ip address of my sql server is set to null can you tell me how to set it ?

  • Mark Hernz Martz

    04-25 10:18:38.284 2916-2996/com.mark.sql E/ERRO: net.sourceforge.jtds.jdbc.Driver
    someone…. help me….. no work…..

  • Raghavendra J Chikkalkar

    Hitesh I tried with all suggestions given by you. But still the connection is returning “null”. Please guide me on this

  • Hound Hunter

    Hiii there i’ve follow your post regarding SQL connection with Android. I followed everything and write the code as it like you just one change which is ip address. Rest of the code and db data is same like you but when i run it it says “Error in connection with SQL server”. Please help you out. letmeupplzhound@gmail.com my mail address please reply. Waiting for your response

    • Hi hound hunter, can you pls say what logcat output you are getting. And also which SQL server version you are using? Is your sql server getting connected directly using IP address of your PC.

      • Hound Hunter

        hi thanks for the reply . I’m gitting below error and i’m using MS SQL server 2014

        andro E/ERRO: Network error IOException: failed to connect to /192.168.1.2 (port 1433): connect failed: ECONNREFUSED (Connection refused)

        • Do this thing..try turning off your computer’s firewall. Also try connecting the sql server using IP address on your pc itself

          • Hound Hunter

            yes my fire wall is turned off already but how can i connect sql by pc itself? I already enabled TCP/IP .

  • BARA TEKNOLOGI

    thanks good tutorial

  • kumar

    Thank You So Much Bro it is working….. after 7-8 days of googling….:-)

  • Cort

    Can You Put the project from android studio

  • Ang Kai

    Hi Hitesh,

    Can u pls help me, this is my logcat when i start running the code
    E/ERRO: net.sourceforge.jtds.jdbc.Driver
    E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f58f7a5ef80

    And bellow is my code, thanks.

    • First copy the Jar file in the “libs” folder.
      And then click on “Add as Library”. Have a look at the pics you will understand it…

      • Here

        • Ang Kai

          Thanks for help!!
          But having another issue there….
          Login failed for user ‘POSSERVERPOS’
          getSlotFromBufferLocked: unknown buffer: 0x7f58f7a60950

          • Is “POSSERVERPOS” your database username, if yes please set the password also.
            And don’t include slashes in username. You can create a new user from sql database > security> login

          • Ang Kai

            thanks!! It’s works!!
            I can access to sql server from my android now!!
            Thanks x9999999999!!!

          • You are welcome.

          • Ang Kai

            Can u do 1 more tutorial for retrieve the data from sql server and bring forward to next page?

          • Use sharedPreferences or Intents

          • Ang Kai

            thanks i used Intents and it’s work!
            one more thing, do you know how adding ListView items with user input from AlertDialog?

          • If the alertdialog box has only one input, you can store the value in sqlite db or for temporary purpose, you can use arrayList string, and use adapter to set the view of the listview data.

          • Ang Kai

            thanks ya!!
            But i’m not really understand, can u do a simple tutorial? grateful!!

          • What you want is a alert dialog with a textbox in it and a listview in which a item will be added upon clicking OK, right? Let me know!!

          • Ang Kai

            is something like ordering, when i click on button then will show the foodlist (listview), then when i click the items of foodlist will pop out the alert dialog to ask u to key in quantity and price, after i click OK then will show the list at below or next page.

          • Ang Kai

            Hi sir,
            one more question to ask u, is it possible to pass data from sqlite to sql server without any web services or third party?

          • sushma rani

            unable to connect sql server
            error show in error in connection with sql server

  • Kashif Faraz

    How to reslove it!
    java.sql.SQLException: The USE database statement failed because the database collation Urdu_100_CI_AI is not recognized by older client drivers. Try upgrading the client operating system or applying a service update to the database client software, or use a different collation. See SQL Server Books Online for more information on changing collations.

  • sushma rani

    error show error in connection with sql server

    • What is the logcat output?

      • sushma rani

        my log category

        • This is not the logcat output for the application

          • sushma rani

            Logcat

      • sushma rani

        my logcat

      • sushma rani

        logcat error

  • Kashif Faraz

    I successfully connect sql server with my android app but when i install my app on my phone , application crash after click login button

  • Kiranchand Samantaray

    where is AddProducts.class ???

  • Kiranchand Samantaray

    It ive comilation error at .AddProduct

  • Kiranchand Samantaray

    This line Intent i = new Intent(MainActivity.this, AddProducts.class); in MainActivity.java and line android:name=”.AddProducts” in AndroidManisfest.xml giving ERROR

  • ankur tomar

    my database stored on a server , so when i connect my android app with server database with local IP it works only on same network but when i connect my application with server external IP then it does not connect with the server databse. plz help me to rectify the problem.

    • See, your PC is not a server or you haven’t made your Database available through a network IP or website URL. For example when you are accessing my website the data is coming from a database backend which is accessed through a network by which you and my website is connected i.e. The internet.
      So when you type your Local IP, your PC is accessible since you’re both in the same network maybe Wifi or same Lan network. But your PC is not accessible outside this network, for example I can’t access your PC’s database via my PC or laptop because we are not in the same network. Hope it helps. To access it outside your local network and through internet, you will have to host your database in the internet hosting space.

      • ankur tomar

        I understand buddy but i told you earlier that i have that internet hosting space and i upload the database there but i didnt connect with it through the web server ip .
        it works only on the local server IP.

        • ankur tomar

          is there any firewall issue
          that restrict us to get that database data

          buddy every server has two ip one is local and another is webserver ip
          this app works only on local ip on local network but i need to use webserver ip which allow me to access the database with any network

          • ok sorry for wrong comment. I had this issue. There must be a setting in your C Panel setting called Remote management. Just enter IP address of your Internet connection there. Not your PC’s IP address. See what’s my IP in google. It requires to enter the IP address of my home’s internet connection, in the setting my internet hosting provider provided me or else my app doesn’t connect.

          • ankur tomar

            This App is not working and I cant change the Cpanel setting, My server IP is differ from the IP get from google. what to do i cant linked with that IP
            Internal IP works but on same network
            External IP is differ from the IP get from Google
            I want this app to access from all the network.
            please solve it out .

          • It’s not possible, there must be setting called remote management or remote access in your C Panel setting. I’m not saying to change your server’s IP address but to add your IP address in the remote management section to allow access.

          • ankur tomar

            but the problem is google gave me the IP which is already work somewhere.
            and I didn’t have knowledge about how to add IP in Cpanel setting.

          • ankur tomar

            On My Public IP my official website worked on it and use the database
            but when I Connect that App with the IP it cant work
            and Google Gave me some another IP
            (In Both Public IP there is only last digit different.)

          • kaise possible hein ye. Every internet connection has got different IP address, yes only last sequence is different. Show when you type Whats my IP in google, it’ll show you your connection’s Ip address. And you have to add this in your setting options. Ok this is one thing.
            And the other is, you are having PHP hosting or .NET hosting plan. If MS SQL is there there must be connection string like “xxx.myconnection.con.xxx” or something like that. Use that it must work. Ip address is not always important.
            And remote management security is not provided by all providers. Contact your provider to see, if you can get access remotely of your database.

          • ankur tomar

            sir kya hum is program me ip ki jagah server name se access kar sakte hai
            jo website ka databse jis public ip se work karta hai vo public ip se connction nahi ho raha hai

            google se jo public ip mili hai vo diffrnt hai so
            cpanel setting me mujhe kis public ip ko add karna hoga apne local or intrnal ip se jisse ye aap chale
            i m totally confused

          • Enter the IP address which google provided you, that’s your real IP address

  • akila mani

    hi am getting erro like Io exception: The Network Adapter could not establish the connection
    please help in this.

  • akila mani

    sql exception also occurring for me i used this to connect oracle databse i used ojdbc14.jar file

  • akila mani

    07-04 06:43:23.693 12313-12342/com.example.admin.akila_hrms E/MainActivity: Before connection
    07-04 06:43:23.693 12313-12342/com.example.admin.akila_hrms E/ConnectionClass: After dbUrl
    07-04 06:43:59.743 12313-12342/com.example.admin.akila_hrms E/ERRO: Io exception: The Network Adapter could not establish the connection
    07-04 06:43:59.743 12313-12342/com.example.admin.akila_hrms E/ConnectionClass: sql
    07-04 06:43:59.743 12313-12342/com.example.admin.akila_hrms E/MainActivity: After connection
    07-04 06:43:59.743 12313-12342/com.example.admin.akila_hrms E/MainActivity: Inside connection

    this is my logcat please do the need ful help as soon as possible

    • ต้อง รัก

      try check service in your sql is open or not

  • Ramesh Krishnan

    hi hitesh, am getting and sql connection error message. its coming on executing class.forname(classs), exception e is class not found exception net.sourceforge.jtds.jdbc.driver, i have included this driver in my project from this link, can u plse help me out to solve this problem.

    • Please click on add as library if you are using android studio.

      • Ramesh Krishnan

        thanks its working…

  • Medha Sharma

    A lot of people on the net suggest that connecting directly to the database raises security concerns as anyone can recompile the code and get the database password. So, the code provided above, is it secure? If not, can you provide a sample code using Web Service or adding a layer in between which makes the code secure?

    • I get lots of questions about security concerns regarding providing password and username in your code itself.
      I’ll say you should use ProGuard in your application code :
      https://developer.android.com/studio/build/shrink-code.html
      Also regarding webservices, I know about .net services, I can help you regarding .net services. If so let me know.

  • Medha Sharma

    If you can send/post the code with making the connection to the database via .net services/java web service such as KSoap , it will be fantastic.

  • ShariQ Bharat

    I have used above code. Getting below error. Help me to resolve.
    com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: “Socket closed”. ClientConnectionId:

  • ShariQ Bharat

    By using above code I am able to make connection to my db but unable to fetch records from table.
    Getting below error-
    java.sql.SQLException: Invalid object name ‘ford.TripTable’. where ford is schema name and triptable is table name.
    I have created database on Microsoft Azure cloud server.

  • philzon

    Hi Hitesh, I have set up everything correctly in my laptop and everything is running fine via wifi. I want to know using this code will I be able to update Database through mobile Internet?. I have an Interview tomorrow and they are expecting to update database via internet? what all changes should I make if any? Please reply.

    • For mobile internet you have to host the database on internet.

  • Nikhil

    Getting error ” android:background=”@drawable/btnbg”

    Error:(58, 33) No resource found that matches the given name (at ‘background’ with value ‘@drawable/btnbg’).

    If I remove this line “” android:background=”@drawable/btnbg”” then getting other error

    Error:(29, 25) error: package R does not exist

    • Kulwinder Singh Dhiman

      Hi Nikhil

      facing same error
      did you get any solutions?

      • ต้อง รัก

        try delete android:background=”@drawable/btnbg

  • Muhammed Irfan

    I have created a small android app using this.I am able to connect to database by creating the object of connectinclass and calling the CONN() method. I am connecting to database the same way in 2 or 3 activities. but after few clicks in the app, the database connection not working. it says the error: E/ERRO: I/O Error: DB server closed connection. in the log cat. Can anyone help me with this? I got blocked here.

  • mojtaba Ashkufaraz

    Hi
    I has a data base on server (91.241.21.21;)
    and i can connect to sql server with sql server managment and all things is ok but with android all time con is null?
    Connection con = connectionClass.CONN();
    if (con == null) {
    z = “Error in connection with SQL server”;
    }
    all time say “Error in connection with SQL server”

    • ต้อง รัก

      check value in class ConnectionClass

      i think something is wrong. or can i see your code in ConnectionClass?

      • mojtaba Ashkufaraz

        thank you.this problem sloved

        • Weng Tan

          can i know how you solved? i also having the same problem.

  • Shaiwal Tripathi

    Hi Hitesh
    First of all thank you for nice code. I got an error “Error in connection with SQL server” at the time of login so When I debug my code then found this exception
    “class not found exception net.sourceforge.jtds.jdbc.driver”
    I did the same thing as you guided in your post. Can you please help ?

    • Sepaka Hlongwane

      Hello there,
      This is most probably because you did not add the JDBC jar file to your application.
      Add the jar file to your libs directory and ensure that you you add a reference to it on build.gradle under dependencies as follows:

      compile files(‘libs/YourJDBCdriverName.jar’)

  • ต้อง รัก

    ConnURL = “jdbc:jtds:sqlserver://” + ip + “;”
    + “databaseName=” + db + “;user=” + un + “;password=”
    + password + “;”;

    change at + ip + “;” to + ip + “/”

    ex.

    ConnURL = “jdbc:jtds:sqlserver://” + ip + “/”
    + “databaseName=” + db + “;user=” + un + “;password=”
    + password + “;”;

    if you use “;” db will use master database in sql instead of Andro

    i fix it !!!

  • Kwang Su Choi

    I am getting “invalid object name” for “Usertbl” when writing script for DB Andro. Can anyone help? I am copying exactly what it says on the website

    • Mohammed Alajmi

      you can delete second row :
      select * from Usertbl

      after that try to run script

    • ต้อง รัก

      can i see your script?

  • Cygneis

    Hi, I followed the tutorial, but i have this error: E/ERRO: Network error IOException: failed to connect to /185.28.20.60 (port 1433): connect failed: ETIMEDOUT (Connection timed out).

    Does someone know where does this error come from ?

  • vishal

    Hi sir…m gettibg error like ” Error in connection with SQL server” n in LOgcat it showing error “net.sourceforge.jtds.jdbc.Driver”;

  • vishal

    Cannot make a static reference to the non-static method CONN() from the type ConnectionClass

    • ต้อง รัก

      can i see your code? in ConnectionClass

      • vishal

        oh sure sir….!!!!

        my connection class code is as below:)

        public class ConnectionClass
        {
        String ip = “192.168.1.10”;
        static String classs = “net.sourceforge.jtds.jdbc.Driver”;
        String db = “EmpAttn”;
        String un = “vishu”;
        String password = “vishu”;
        @SuppressLint(“NewApi”)
        public static Connection CONN() {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()

        .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection conn = null;
        String ConnURL = null;
        try {

        Class.forName(classs);
        ConnURL=”jdbc:jtds:sqlserver://localhost:1433;databaseName=TEST;integratedSecurity=true; “;
        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;
        }
        }

        • ต้อง รัก

          try change syntax ConnURLto

          ex.

          ConnURL = “jdbc:jtds:sqlserver://” + ip + “/”
          + databaseName + “;user=” + un + “;password=”
          + password + “;”;

          • vishal

            i tried…bt ll u plz edit ma ConnUrl …??

          • ต้อง รัก

            now u get error?

          • vishal

            my MAIN ACTIVITY code is as below:

            import ConnectionClass.ConnectionClass;
            import android.app.Activity;
            import android.content.Intent;
            import android.os.AsyncTask;
            import android.os.Bundle;
            import android.view.View;
            import android.widget.Button;
            import android.widget.EditText;
            import android.widget.ProgressBar;
            import android.widget.Toast;

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

            public class MainActivity extends Activity {

            ConnectionClass connectionClass;
            EditText edtuserid,edtpass;
            Button btnlogin;
            ProgressBar pbbar;

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

            connectionClass = new ConnectionClass();
            edtuserid = (EditText) findViewById(R.id.edtuserid);
            edtpass = (EditText) findViewById(R.id.edtpass);
            btnlogin = (Button) findViewById(R.id.btnlogin);
            pbbar = (ProgressBar) findViewById(R.id.pbbar);
            pbbar.setVisibility(View.GONE);

            btnlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            DoLogin doLogin = new DoLogin();
            doLogin.execute(“”);

            }
            });

            }

            public class DoLogin extends AsyncTask
            {
            String z = “”;
            Boolean isSuccess = false;

            String userid = edtuserid.getText().toString();
            String password = edtpass.getText().toString();

            @Override
            protected void onPreExecute() {
            pbbar.setVisibility(View.VISIBLE);
            }

            @Override
            protected void onPostExecute(String r) {
            pbbar.setVisibility(View.GONE);
            Toast.makeText(MainActivity.this,r,Toast.LENGTH_SHORT).show();

            if(isSuccess) {
            Intent i = new Intent(MainActivity.this, AddProducts.class);
            startActivity(i);
            finish();
            }

            }

            @Override
            protected String doInBackground(String… params) {
            if(userid.trim().equals(“”)|| password.trim().equals(“”))
            z = “Please enter User Id and Password”;
            else
            {
            try {
            Connection con = ConnectionClass.CONN();

            if (con == null) {
            z = “Error in connection with SQL server”;
            } else {
            String query = “select * from Login where UserName='” + userid + “‘ and Password='” + password + “‘”;
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(query);

            if(rs.next())
            {

            z = “Login successfull”;
            isSuccess=true;
            }
            else
            {
            z = “Invalid Credentials”;
            isSuccess = false;
            }

            }
            }
            catch (Exception ex)
            {
            isSuccess = false;
            z = “Exceptions”;
            }
            }
            return z;
            }
            }
            }

            connection class code is:

            import java.sql.Connection;

            import java.sql.DriverManager;
            import java.sql.ResultSet;

            import android.annotation.SuppressLint;
            import android.database.SQLException;
            import android.os.StrictMode;
            import android.util.Log;

            public class ConnectionClass
            {
            String ip = “192.168.1.10”;
            static String classs = “net.sourceforge.jtds.jdbc.Driver”;
            String db = “EmpAttn”;
            String un = “vishu”;
            String password = “vishu”;
            @SuppressLint(“NewApi”)
            public static Connection CONN() {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()

            .permitAll().build();
            StrictMode.setThreadPolicy(policy);
            Connection conn = null;
            String ConnURL = null;
            try {

            Class.forName(classs);
            ConnURL=”jdbc:jtds:sqlserver://localhost:1433;databaseName=TEST;integratedSecurity=true; “;
            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;
            }
            }

          • ต้อง รัก

            you add jtds-1.2.7.jar library file to your application right?

          • vishal

            yes

          • ต้อง รัก

            add this

            ConnURL = “jdbc:jtds:sqlserver://” + ip + “/”
            + databaseName + “;user=” + un + “;password=”
            + password + “;”;

            instead of your code ConnURL in ConnectionClass

            ConnURL=”jdbc:jtds:sqlserver://localhost:1433;databaseName=TEST;integratedSecurity=true; “;

          • ต้อง รัก

            localhost cant use in this

            should add IP instead of localhost

          • vishal

            i ll try now….thank u

          • Erik Fok

            Create an instance of the Connection class, for example
            ConnectionClass myConnectionClass = new ConnectionClass();
            Connection con = myConnectionClass.CONN();

            or just reference the one institiated at the top.

          • vishal

            i tried….now m getting error like diz

            Error in connection with SQL server” n in LOgcat it showing error “net.sourceforge.jtds.jdbc.Driver”;

  • Mandeep Negi

    Hii ,

    I have copied this code but i am getting this error : E/ERRO: net.sourceforge.jtds.jdbc.Driver
    can anyone help me here

  • Soumyajyoti Gupta

    ConnectionClass connectionClass;
    Its showing cannot resolve the symbol Connectionclass
    Connection con = connectionClass.CONN();
    Its showing cannot resolve the symbol CONN
    What to do?

    • Soumyajyoti Gupta

      problem solved

  • Soumyajyoti Gupta

    another problem when i open the application clicking the button enables the progress bar bt nothing happens

    • ต้อง รัก

      can you show your logcat when you click button? i will help u

      • Soumyajyoti Gupta

        it says error in sql connection

        • ต้อง รัก

          can u copy your text error in logcat? i want to see more

      • Soumyajyoti Gupta

        import android.app.Activity;
        import android.content.Intent;
        import android.os.AsyncTask;
        import android.os.Bundle;
        import android.view.View;

        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.ProgressBar;
        import android.widget.TextView;
        import android.widget.Toast;

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

        public class Login extends Activity {
        Button b1;
        EditText ed9,ed7;

        TextView tx9,tx14;
        ConnectionClass connectionClass;
        ProgressBar pbbar;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        b1 = (Button) findViewById(R.id.button);
        ed9 = (EditText) findViewById(R.id.editText9);
        ed7 = (EditText) findViewById(R.id.editText7);
        tx9 = (TextView) findViewById(R.id.textView9);
        tx14 = (TextView) findViewById(R.id.textView14);
        pbbar = (ProgressBar) findViewById(R.id.progressBar3);
        pbbar.setVisibility(View.GONE);

        connectionClass= new ConnectionClass();

        pbbar = (ProgressBar) findViewById(R.id.progressBar3);
        pbbar.setVisibility(View.GONE);

        b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        Login.DoLogin doLogin = new Login.DoLogin();
        doLogin.execute(“”);

        }
        });

        }

        public class DoLogin extends AsyncTask {
        String z = “”;
        Boolean isSuccess =false;

        String userid = ed7.getText().toString();
        String password = ed9.getText().toString();

        @Override
        protected void onPreExecute() {
        pbbar.setVisibility(View.VISIBLE);
        }

        @Override
        protected void onPostExecute(String r) {
        pbbar.setVisibility(View.GONE);
        Toast.makeText(Login.this, r, Toast.LENGTH_SHORT).show();

        if (isSuccess) {
        Intent i = new Intent(Login.this, Welcome.class);
        startActivity(i);
        finish();
        }

        }

        @Override
        protected String doInBackground(String… params) {
        if(userid.trim().equals(“”)|| password.trim().equals(“”))
        z = “Please enter User Id and Password”;
        else
        {
        try {
        Connection conn = connectionClass.CONN();
        if (conn == null) {
        z = “Error in connection with SQL server”;
        } else {
        String query = “select * from login where emp_code='” + userid + “‘ and pass='” + password + “‘”;
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);

        if(rs.next())
        {

        z = “Login successfull”;
        isSuccess=true;
        }
        else
        {
        z = “Invalid Credentials”;
        isSuccess = false;
        }

        }
        }
        catch (Exception ex)
        {
        isSuccess = false;
        z = “Exceptions”;
        }
        }
        return z;
        }
        }

        }

      • Soumyajyoti Gupta

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

        public class ConnectionClass {
        String ip = “192.168.0.105”; ////DIS2008R2
        String classs = “net.sourceforge.jtds.jdbc.Driver”;
        String db = “cmms”;
        String un = “table_user”;
        String password = “tables”;

        @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(classs);
        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;
        }
        }

  • Soumyajyoti Gupta

    i am having a problem in a code in which i am trying to convert a string in ascii value and thn insert the ascii value into a database. please can anyone help?

  • Loren

    hai anyone.. I follow the tutorial for connect Android Studio 2.2.3 and MS SQL server 2012, but i have this error : “Error in connection with SQL server”.. can you help me please?

  • Mr Kang

    hello sir i use this code
    http://www.parallelcodes.com/connect-android-to-ms-sql-database-2/

    i use IP String ip = “208.91.198.174:1433”;
    i see Error

    Error in connection with SQL server

    pls help me

  • deniz

    if(isSuccess) {
    Intent i = new Intent(MainActivity.this, AddProducts.class);
    startActivity(i);
    finish();
    }

    i didnt understand Addproducts.class error. we didnt create like that what is it?

  • ashik

    Statement stmt = conn.createStatement();

    where createStatement(); is causing error, please help me

  • Joe

    I have a connection error. Can anyone help.
    I do have the JTDS-1.2.7.jar file in a libs folder

    I also am getting this warning which may be causing the problem but i’m not sure.
    Error:warning: Ignoring InnerClasses attribute for an anonymous inner class
    Error:(net.sourceforge.jtds.jdbc.CharsetInfo$1) that doesn’t come with an
    Error:associated EnclosingMethod attribute. This class was probably produced by a
    Error:compiler that did not target the modern .class file format. The recommended
    Error:solution is to recompile the class from source, using an up-to-date compiler
    Error:and without specifying any “-target” type options. The consequence of ignoring
    Error:this warning is that reflective operations on this class will incorrectly
    Error:indicate that it is *not* an inner class.

    • Caolán Ó Dálaigh

      hi

      have you got a solution to this? im having the same issue now

      • Download from the link provided and import it as library in your Android studio project or copy in your Libs folder if you are using Eclipse ADT.
        http://www.java2s.com/Code/Jar/j/Downloadjtds131jar.htm
        Hope this helps.

      • Joe

        My problem turned out to be a port issue

        • Aaiinii

          hi, then how u solve the problem ? i’m having the same error as u stated above.

  • Ammar Musleh

    Can i access this database globally even when connected to other networks or does it work on the same network?

    • Yes you can. I’m using this for my professional work too.

  • Tabraiz Ahmed

    I am using this solution to connect my SQL SERVER, i did all same as mentioned but now the issue is that when i click login button it say “UNFORTUNATELY APP HAS STOPPED”.
    please help anyone

  • Kulenthirarajah Kobishanth

    it gives as error JSR/RET are not supported with compute frame options

  • Pingback: Can’t connect to SQL server from Android studio()

  • Weng Tan

    I follow your everystep but I still cannot login. I found that the error occur when i put my ip address eg, 192.168.1.111 and it will show exception. However, when i add TCP port behind the ip address it show “error in connection with sql server.” Can you help me ?

    • Aaiinii

      Have u solve the problem ? May i know the solution ? because my apps also show exceptions.

  • ani

    Thank you so much for this great tutorial ! I’m able to run it 🙂

  • Душан Радосављевић

    I have this sqlServerException

    Network error IOException: Connection refused:
    can you help me

  • Vijay Sutariya

    Hi Hitesh,

    Thanks for your wonderful post, I cant resist my hand to write a thank full.

    regards
    vijay sutariya

  • Manisha Khatke

    when i am connecting from IP address its working successfully but when i am connecting from server name i am getting below error

  • Manisha Khatke

    when i am connecting from IP address its working successfully but when i am connecting from server name i am getting below error
    Unknown server host name ‘Unable to resolve host “SERVER-NAME”: No address associated with hostname

    • It will not connect with server name. The code requires a URL or IP address to send connection request.

      • Manisha Khatke

        but when i am connecting from ip addres its connected successfully but it only work in same network.
        Not connecting from other network.

  • safiya akhtar

    thank you for this code but this code is running on my emulator nexus4 API 24 but not on my andrid real device , it gives sql server connecion error in toast everytime i try to login. Can you please help me with this

  • Хикмат Шайхалиев

    please send me th complete code to hikmat0495@gmail.com

  • amit

    Logcat showing the error “Network error IOException: Connection timed out”. kindly help me….

  • Sana

    What is AddProducts.class in MainActivity?

  • Neeraj soni

    thanks for this tutorial. sir i have successfully connected with ms sql in android, but i have a question can you please help me? my question is how to fetch the information from data base and show in textview in another activity in navigation drawer in android.i have put my query in second activity. but it was not showing in textview.

  • Fathima Salim

    What is AddProduct class? Should I create new activity named AddProduct? Its an error(Unresolved class AddProduct)