17

Is there a way that we can connect an Android application to a central database server (e.g. MSSQLServer 2008)?

I have a MySQL database that is accessed by both website and Android. Connecting to the database from the website is fine, but how can it be done from the Android app?

0

7 Answers 7

22

here are some similar questions asked (an answered):

Even though those are for MySQL, it should work for MSSQL by changing the engine or the driver's use to connect. Usually, the approach is to expose some limited level of modification through a web service. Still, nothing is stopping you from directly accessing the database, albeit depending on the case, could pose a security risk.

Main Reasons the web service approach is taking:

  • Performance
  • Security
  • Best Practice
  • Separation of concerns

An exception is if you want to enable direct access because you're building a sort of database client through mobile.

2
  • 2
    linke u give here here are not for sql server 2008 they are just for mysql server. u should know difference between sql server and mysql database Commented Oct 19, 2013 at 15:38
  • 7
    @DPM if you read the answer, it is actually database agnostic, so it does not matter.
    – eis
    Commented Nov 15, 2013 at 9:42
5

All you have to do is use the appropriate driver, i'd recommend using JTDS, and version 1.2.5 seems to have worked well with android.Detailed instruction on how to use with eclipse can be found here A working code is available in github

/**
 * This is a demo code to demonstrate db connection and operations and not 
 * meant for a live run. 
 * 
 */

public class DBTestActivity extends Activity {

    private Connection conn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dbtest);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.dbtest, menu);
        return true;

    }
    @Override
    protected void onResume() {

        super.onResume();
        (new DBConnection()).execute(null, null, null);

    }

    @Override 
    protected void onPause() {

        super.onPause();
        try {

            conn.close();

        } catch (SQLException e) {

            e.printStackTrace();

        }

    }
    class DBConnection extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... arg0) {

            try {

                Log.e("MSSQL", "Attempting to connect");

                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                conn = DriverManager.getConnection(
                        "jdbc:jtds:sqlserver://yourserver.com/DBName",
                        "username", "password");

                Log.e("MSSQL", "Connected");

            } catch (Exception e) {

                e.printStackTrace();
                Log.e("MSSQL", e.toString());

            }

            return null;
        }

    }

    class UserInfo {

        String userID;
        String userName;
        String PhoneNo;
        String age;

        public UserInfo(String userID, String userName, String PhoneNo,
                String age) {

            this.userID = userID;
            this.userName = userName;
            this.PhoneNo = PhoneNo;
            this.age = age;

        }

        public String getUserID() {
            return userID;
        }

        public void setUserID(String userID) {
            this.userID = userID;
        }

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }

        public String getPhoneNo() {
            return PhoneNo;
        }

        public void setPhoneNo(String phoneNo) {
            PhoneNo = phoneNo;
        }

        public String getAge() {
            return age;
        }

        public void setAge(String age) {
            this.age = age;
        }

    }

    class DBOperation {

        public List<UserInfo> getAllUsers() throws SQLException {

            Statement statement = getStatement(conn);

            List<UserInfo> userlist = new ArrayList<UserInfo>();

            ResultSet rs = statement.executeQuery("SELECT * FROM UserInfoTable");
            rs.next();
            int count = 0;

            while (rs.next()) {

                userlist.add(new UserInfo(rs.getString(1), rs.getString(2),
                        rs.getString(3), rs.getString(4)));
                count++;

            }

            rs.close();
            statement.close();
            return userlist;

        }

        public void addUser(UserInfo info) {

            Log.e("MSSQL", "in adduser");

            Statement statement = getStatement(conn);

            try {

                ResultSet rs = statement.executeQuery("INSERT INTO UserInfoTable "
                        + " VALUES ('1001', 'Bob', '333333', '33')");
                rs.close();
                statement.close();

            } catch (SQLException e) {

                e.printStackTrace();

            } 

        }

        private Statement getStatement(Connection connection) {

            try {

                return connection.createStatement();

            } catch (Exception e) {

                throw new RuntimeException(e);

            }
        }

    }

}
1
  • Hi, I tried using your sample code but whenever I launch the application, the system keep giving me this error "Charset 0x0904000128/Cp850 is not supported by the JVM", I had tried connecting to the database in Java and it works fine but only in java android it gives me error . May I know what version of eclipse you are using ? Is it Eclipse ADT Juno? Commented Nov 12, 2014 at 5:07
3

An other approach, musch simpler than Web Service, is to use a Virtual JDBC Driver that uses a three-tier architecture: your JDBC code is sent through HTTP to a remote Servlet that filters the JDBC code (configuration & security) before passing it to the SQL Server JDBC Driver. The result is sent you back through HTTP. There are some free software that use this technique. Just Google "Android JDBC Driver over HTTP".

2

Connecting your android application directly to an external database server is a bad idea, instead create a web application and access the database through that.

7
  • thanks Dre....actually i wanted to populate my app with the data stoed in central database ( which is common to my website ) ..please help
    – Jasra
    Commented Mar 10, 2011 at 5:54
  • 1
    Then update your question, accessing databases and accessing websites are two different things.
    – Dre
    Commented Mar 10, 2011 at 5:57
  • see basically i have a database which is accessed by both website and android.....database used is my sql server .Connecting database to website is fine but how it can be done through android app??
    – Jasra
    Commented Mar 10, 2011 at 5:58
  • You do not connect android to database, you connect android to website to database. Having your database credentials in your application is a very bad idea as anyone can get access to them.
    – Dre
    Commented Mar 10, 2011 at 6:01
  • could you please tell me how to connect android to website to database...Thankss a lot!!
    – Jasra
    Commented Mar 10, 2011 at 6:04
2

There are a number of strategies you can employ to accomplish what you want to do. Given that the SOAP support for Android is non-existent, you're going to most likely want to push the data out in either XML or JSON format through WCF, ASP.NET, Ruby On Rails, PHP or any number of web frameworks.

Without knowing what your web application is currently running, it's hard to say how to best make that data connection. You can use WCF Data Services if you want to get up and running as fast as possible, and MSDN has a decent article on getting started with it:

http://msdn.microsoft.com/en-us/library/cc668792.aspx

I suggest that you examine your existing solution and figure out how to best extend that to push data out to your Android app.

0
1

i've try to connect android via PHPto ms sql server, you can read here,am using httprequest and json. If you want to connect to Ms SQL Server 2005 or higher, you must download Microsoft Driver for PHP for SQL Server.

I've used php as web service to connect Ms SQL Server database, anyway you can used jdbc to connect from android direct to MS SQL Server database

0
0

If you need to do that probably you donìt have already a 3 tier architecture. If this is the case consider writing a mobile web application. I did that to add mobile interface to a client server 2 tier legacy system.

I had a legacy Delphi client/server app, and i created by using Raudus a web app optimized for mobile devices. Of course this makes sense if you have Delphi skills, but for other languages/tecnhologies there are the coutnerparts.

Not the answer you're looking for? Browse other questions tagged or ask your own question.