Android – How to connect to mssql server using jdbc in android emulator

androidsql server

I am a beginner to android development. now am trying to connect with MS SQL 2008 R2 via emulator.MS SQL 2008 R2 running on another (server) machine. Am getting the following error:

The TCP/IP connection to the host xxx.xxx.xx.x\SQL2008R2DEV has failed; 
error: null;
verify connection properties.
make sure that instance of SQL server running on the host and accepting TCP/IP connection to the port are not blocked by Windows Firewall.

Note I have done this in java application. and also I can access my database.
but why cannot in android program?
have any idea?

NOTE: BOTH SERVER AND MY PC ARE CONNECTED VIA LAN.

Best Answer

Yes it is possible to connect to MSSQL from android emulator. For example if the other system is having IP 192.168.1.2 then you can very use the same IP in your emulator to connect to the database. Anyway using JDBC in android is not encouraged. This link will explain why it not advisable to use JDBC in Android. This is how you can connect to MSSQL database using JDBC:

    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
        Connection conn =DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=msdibya;user=dibya;password=dibya;");                   

        System.out.println("connected");
        Statement statement=conn.createStatement();
        ResultSet resultSet=statement.executeQuery("select * from [user]");
        while(resultSet.next()){
            System.out.println(" "+resultSet.getString(1)+" "+resultSet.getNString(2));
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

I hope you have the proper jar files. Don't forget to import them.