0

I am connecting android to SQLServer directly (I know its not recomended)

I have written following code:

public class MainActivity extends Activity {


     String dbName = "AndroidDB";
     String serverip="10.0.2.2";
     String serverport="1433";
     //String url = "jdbc:sqlserver://14GRAFICALI\\MSSQLSERVER2008;databaseName="+dbName+"";
     //String url ="jdbc:sqlserver://14GRAFICALI\\MSSQLSERVER2008;databaseName=AndroidDB;integratedSecurity=true";
     String url ="jdbc:sqlserver://14GRAFICALI;instanceName=\\MSSQLSERVER2008;DatabaseName=AndroidDB;integratedSecurity=true";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        TextView tvData=(TextView)findViewById(R.id.tvSelectedData);

        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
            Class.forName("javax.sql.XAConnection").newInstance();
            Connection conn =DriverManager.getConnection(url);                   

            Statement statement=conn.createStatement();
            ResultSet resultSet=statement.executeQuery("select * from UserMaster");
            while(resultSet.next()){
                tvData.setText(" Data1 : "+resultSet.getString(1)+"  Data 2 : "+resultSet.getNString(2));
            }

        } catch (Exception e) {
            e.printStackTrace();
            tvData.setText(e.getMessage());
        }



    }

Before that i was not having this line:

 Class.forName("javax.sql.XAConnection").newInstance();

But it given me exception on it:

09-07 15:12:20.911: E/dalvikvm(1293): Could not find class 'javax.sql.XAConnection', referenced from method com.microsoft.sqlserver.jdbc.SQLServerConnection.poolCloseEventNotify

Hence i imported a jar containing this file and added it to libraries:

enter image description here

(jboss.jar)

Export:

enter image description here

After this also i am getting error:

java.lang.ClassNotFoundException: javax.sql.XAConnection

I have this class :

enter image description here

I am not understanding why this error is comming. Please help me.

LogCat:

09-07 15:52:52.641: W/System.err(330): java.lang.ClassNotFoundException: javax.sql.XAConnection
09-07 15:52:52.641: W/System.err(330):  at java.lang.Class.classForName(Native Method)
09-07 15:52:52.641: W/System.err(330):  at java.lang.Class.forName(Class.java:234)
09-07 15:52:52.641: W/System.err(330):  at java.lang.Class.forName(Class.java:181)
09-07 15:52:52.641: W/System.err(330):  at com.example.sqlservercall.MainActivity.onCreate(MainActivity.java:33)
09-07 15:52:52.641: W/System.err(330):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-07 15:52:52.651: W/System.err(330):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
09-07 15:52:52.651: W/System.err(330):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
09-07 15:52:52.651: W/System.err(330):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
09-07 15:52:52.651: W/System.err(330):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
09-07 15:52:52.651: W/System.err(330):  at android.os.Handler.dispatchMessage(Handler.java:99)
09-07 15:52:52.651: W/System.err(330):  at android.os.Looper.loop(Looper.java:123)
09-07 15:52:52.651: W/System.err(330):  at android.app.ActivityThread.main(ActivityThread.java:3683)
09-07 15:52:52.651: W/System.err(330):  at java.lang.reflect.Method.invokeNative(Native Method)
09-07 15:52:52.651: W/System.err(330):  at java.lang.reflect.Method.invoke(Method.java:507)
09-07 15:52:52.651: W/System.err(330):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
09-07 15:52:52.651: W/System.err(330):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
09-07 15:52:52.651: W/System.err(330):  at dalvik.system.NativeStart.main(Native Method)
09-07 15:52:52.651: W/System.err(330): Caused by: java.lang.NoClassDefFoundError: javax.sql.XAConnection
09-07 15:52:52.661: W/System.err(330):  ... 17 more
09-07 15:52:52.661: W/System.err(330): Caused by: java.lang.ClassNotFoundException: javax.sql.XAConnection in loader dalvik.system.PathClassLoader[/data/app/com.example.sqlservercall-2.apk]
09-07 15:52:52.661: W/System.err(330):  at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
09-07 15:52:52.661: W/System.err(330):  at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
09-07 15:52:52.671: W/System.err(330):  at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
09-07 15:52:52.671: W/System.err(330):  ... 17 more
09-07 15:52:52.861: I/ActivityManager(61): Displayed com.example.sqlservercall/.MainActivity: +1s503ms
09-07 15:53:00.081: W/ActivityManager(61): finishReceiver called but no pending broadcasts
C Sharper
  • 8,284
  • 26
  • 88
  • 151

2 Answers2

12

I have Sucessfully done the Connection with JTDC Android to SQLServer.

Whoever wants to make connection Direct to SQLServer with android should first remember that "This is not at all the secure way".

Steps I followed:

  1. Remember, JDBC creates SSL problems, JTDC drivers are open source and secure. So use JTDC Drivers.

  2. While using JTDC driver make sure that you are using it with proper version. i.e. JTDC drivers version should match or be confirtable with java version. I used jtds-1.2.5-dist you can get it from anywhere on net.

  3. Paste Jar file to libs folder.

  4. Go to Java Build Path (Right Click on project > Properties) In libraries > Add Externl jars. Import Jar file.

  5. In Order And Export > Check on jtds jar as follows:

(other jars you are watching in pic are not useful)

enter image description here

6 You will have to set SQLServer Login Authentication (Windows Authentication for SQLServer) Screenshot as follows:

enter image description here

7 Configure your SQLServer as follows:

Make TCP/IP and VIA connection enabled.

enter image description here

In TCP/IP Properties Change The port to 1433

enter image description here

8 Then you will have to make Connection URL as:

url="jdbc:jtds:sqlserver://10.0.2.2:1433;instanceName=14GRAFICALI\MSSQLSERVER2008;DatabaseName="+DBName+";integratedSecurity=true;user="+UserName+";password="+Password;

9 From Here you can simply follow the code i give you:

public class gaConnection 
{
String url ="";
Connection conn=null;
Statement statement=null;
ResultSet resultSet=null;
    public void setConnection(String DBName,String UserName,String Password)
    {
        try {
            Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
            url ="jdbc:jtds:sqlserver://10.0.2.2:1433;instanceName=14GRAFICALI\\MSSQLSERVER2008;DatabaseName="+DBName+";integratedSecurity=true;user="+UserName+";password="+Password;
            conn =DriverManager.getConnection(url);
            } catch (Exception e) {
            e.printStackTrace();
            }
    }
    public String showResult()
    {
        String strResult="";
        try
        {
            statement=conn.createStatement();
            resultSet=statement.executeQuery("select * from UserMaster");
            while(resultSet.next()){
               strResult = strResult + " Name : "+resultSet.getString(1)+"  SirName : "+resultSet.getString(2) + "\n";
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return strResult;
    }

}

10 I have made Class For Connection and instantiated it as follows:

 public class MainActivity extends Activity {

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

            TextView tvData=(TextView)findViewById(R.id.tvSelectedData);

            String DBName="AndroidDB";
            String UserName="sa";
            String Password="ok";

            try {gaConnection con=new gaConnection();
                con.setConnection(DBName,UserName,Password);
                tvData.setText(con.showResult());
            } catch (Exception e) {
                e.printStackTrace();
                tvData.setText(e.getMessage());
            }

        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

    }
C Sharper
  • 8,284
  • 26
  • 88
  • 151
  • 3
    First nice and clean solution i find to connect to a MSSQL database from Android with regards to the connection string, thank you! – Adrian Olar Jul 15 '14 at 04:24
  • I am getting confused with 6th step. – Stephen Oct 17 '14 at 05:50
  • @Naruto what is ur confusion? – C Sharper Oct 17 '14 at 05:57
  • 5th step itself its ok.I done it.But while coming to that 6th step I didn't know whats happening.Firstly I have one Database file.It was opened in MS Sql sever 2008.Then I followed your five steps.Added the jtdc jar successfully.Finally I am getting a error while connect to that database file with the help of Ms sql server 2008.That error was network related or instance specific. – Stephen Oct 17 '14 at 06:03
  • @Naruto actually bit busy with my work.. But instance specific means you are failing to connect with database (may be credentials problem..or server which you are using might not be on) – C Sharper Oct 17 '14 at 06:27
  • @ÁngelDiMaría you carry on.I can do that. – Stephen Oct 17 '14 at 06:35
  • Hi @DavidBeckham I tried this solution provided by you but I am getting the following error while making connection. java.sql.SQLException: Network error IOException: failed to connect to /192.168.0.105 (port 1433) after 90000ms – codemaniac Jul 15 '15 at 18:45
  • @codemaniac actually i am .net developer and have done this android thing 2 years back for timepass.. Sorry.. Now after two years i dont remember anything in it.. – C Sharper Jul 17 '15 at 08:14
1

The error occurs because, during development, Eclipse ADT shows you the superset of the Android JRE and the Java SE JRE. XAConnection comes from the latter, not from the JDBC JARs you included.

However, on-device, Android only has its own runtime environment, which does not contain all classes from Java SE. It looks like XAConnection is one the missing ones.

To solve the problem you need to find a library that includes the missing classes required by the JDBC JARs (or make it yourself), or, better yet, use the recommended solution.

I recommend the latter, because I know from experience it can be a royal pain to accomplish the former.

Community
  • 1
  • 1
mikołak
  • 9,605
  • 1
  • 48
  • 70