K C
K C

Reputation: 219

Accessing data in SQL Server 2008 from an Android application

I'm new to Android development and have certain issue which is troubling me a lot, and worse is I haven't found the answer to it yet.

Requirement:

1.) I'm developing Android app using eclipse as my base IDE. I have my data safely residing in SQLserver 2008. I don't want to use SQLite/MySql.

2.)Requirement here says, on a button click the application should talk to the SQLServer 2008 database, fetch data from it and list the data in the view.

Is that possible?? If no then queries below this line are invalid.

Problem:

I tried to google it up providing queries like "Android and sqlserver connectivity",

"extracting data from sqlserver in Android" and ended up getting answers like below and I'm

losing track here.

1.) Some show it using a php scripting for My Sql but i'm using java and SQL Server 2008. I'm not getting the link here.

2.) Some just say we have to use a Web Service to do it. I tried understanding that but none of the examples showed implementing a web service and using it. They just made a call to online available Web Service using KSoap to add 2 numbers.

Query:

Is Web Service the only way in Android to communicate with a DB? If yes then how can i approach it. Can anyone guide me as to

1.) How to create a web service in Android application and call it from java code.

2.) How to talk to SQLServer 2008 DB from the webservice and fetch back the data.

Any help is deeply appreciated, Thanks to all.

Upvotes: 2

Views: 6450

Answers (2)

Hassan Badawi
Hassan Badawi

Reputation: 302

How to connect direct from Android to SQL Server.

  1. You need the jtds-1.2.7.jar library.
  2. Set jtds-1.2.7.jar in libs file

  3. Go to Dependencies and set

    compile files('libs/jtds-1.2.7.jar')
    
  4. Create Connect_to_server.class

    import android.annotation.SuppressLint;
    import android.os.StrictMode;
    import android.util.Log;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    public class Connect_to_server {
        @SuppressLint("NewApi")
        public static Connection ConnectionHelper() {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(policy);
            Connection connection = null;
            String ConnectionURL = null;
    
            String user = ***LOGIN_HERE***;
            String password = ***PASSWORD_HERE***;
            String database = ***DATABASE_NAME_HERE***;
            String server= ***SERVER_NAME_HERE***;
    
            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;
        }
    }
    
  5. In any other class or activity you need these three things

    • Connection
    • Statement
    • ResultSet
    1. Let's see how to use with this simple code

      Connection connect;
      Statement st;
      Statement st1;
      ResultSet rs;
      
      btn_Register.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                  try {
                      connect = Connect_to_server.ConnectionHelper();
                      st = connect.createStatement();
      
                      // TODO I will take ID_Admin from here
                      rs = st.executeQuery("  SELECT * FROM [dbo].[AdminUsers]  WHERE Email = N'"+ET_email.getText()+"' ");
      
                      if (rs.next()){
                          Toast.makeText(getApplicationContext(),rs.getString("Email")+"this email in database",LENGTH_LONG).show();
                          Intent i = new Intent(RegisterActivity.this , LoginActivity.class);
                          startActivity(i);
                          finish();
                      }else{
                          reg();
                      }
                  } catch (Exception e) {
                      Log.e("ERRO", e.getMessage());
                  }
              }
          });
      
      private void reg(){
          try {
              connect = Connect_to_server.ConnectionHelper();
              st1 = connect.createStatement();
      
              st1.execute("INSERT INTO [dbo].[AdminUsers]" +
                      "           ([UserAdmin]" +
                      "           ,[PassAdmin]" +
                      "           ,[Address]" +
                      "           ,[Phone]" +
                      "           ,[Email])" +
                      "     VALUES" +
                      "           (N'"+ET_name.getText()+"'" +
                      "           ,N'"+ET_password.getText() +"'" +
                      "           ,N'"+ET_address.getText()+"'" +
                      "           ,N'"+ET_phone.getText()+"'" +
                      "           ,N'"+ET_email.getText()+"' )");
              Toast.makeText(getApplicationContext(),ET_name.getText()+"welcome ",LENGTH_LONG).show();
              Toast.makeText(getApplicationContext(),"u can login now",LENGTH_LONG).show();
              Intent i = new Intent(RegisterActivity.this , LoginActivity.class);
              startActivity(i);
              finish();
          } catch (Exception e) {
              Log.e("ERRO", e.getMessage());
              Log.e("ERRO", e.getMessage());
          }
      }
      
    2. As we saw, we use st.executeQuery when we want to get data back and we set it in ResultSet, then fetch result set

      • while(rs.next()) when we have multiple records
      • if(rs.next()) when we are sure it's only one record
    3. st1.execute without return --- delete - insert - update

    4. rs.getString("***Column_name_HERE***")

Upvotes: 2

savanto
savanto

Reputation: 4550

This is a common topic on stackoverflow, you can find more information by searching.

The typical approach to your problem is to implement an Http API which will run on your server, perform database lookups, and respond to requests by clients, such as your Android application. This way, you will not need to write any code to get your Android app to talk to your SQL server, but will instead be making standard Http requests, which is built-in on Android. On the other hand, you will need to write backend server code to handle these requests and respond with data from the database.

So yes, you will probably need to implement a web server layer between the database and the Android client. It is possible to do it in Java or many other languages, you are not limited to Java just because your client is an Android app.

Someone has already provided some information on just this topic here:
Connect to sql server from android
Connecting android with MS SQL SERVER 2008

Upvotes: 1

Related Questions