Search code examples
javaandroidsql-servereclipsejtds

Connecting android app to Microsoft SQL server 2008


First of all. I am new to android application development environment and I am trying to connect to mssqlserver 2008 with simple android application using jtds-1.3.1.jar driver . I googled many example on internet but i failed to connect with database .
The exception i am getting is Network error IOException: connection time out
I don't know what is wrong with my code i am using Eclipse juno IDE.
here is my code

package com.example.Testproject1;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.widget.TextView;
import java.sql.*;


public class MainActivity extends ActionBarActivity {



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


    public void connectTodatabase()
    {
        TextView txtView=(TextView)findViewById(R.id.textView2);
        String url = "jdbc:jtds:sqlserver://XXX.XXX.X.XXX:1433;DatabaseName=VautomateuShoppi";
        String driver = "net.sourceforge.jtds.jdbc.Driver";
        String userName = "VShopping_User";
        String password = "VShopping_Pass";   
        // Declare the JDBC objects.
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
    try
    {

        // Establish the connection.
        Class.forName(driver);
        con = DriverManager.getConnection(url, userName, password);
            // Create and execute an SQL statement that returns some data.
            String SQL = "select * from SeoMaster";
            stmt = con.createStatement();
            rs = stmt.executeQuery(SQL);

            // Iterate through the data in the result set and display it.
            while (rs.next()) {
                txtView.setText(rs.getString(2));
            }
    }
    catch(Exception ex)
    {
        txtView.setText(ex.getMessage().toString());
    }
    }
}

Solution

  • add these code

    StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);