How to connect and access SQL Database server from Android app??

Recently I have tried to connect to SQL Database server which is in my local network machine. I can connect and access SQL server from my Android app. I did it in the following way….

1. First of all you need a JDBC driver library for SQL Server. As we know android library has only SQLite database driver. So first download an open source JDBC driver from this http://jtds.sourceforge.net/ site (I downloaded the Linux version).

2. Then import the jar file into your Android app.(jtds-1.2.5.jar).

3. Now just try this code by modifying according to your context

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import net.sourceforge.jtds.jdbc.*;

public void query2()
{
Log.i("Android"," MySQL Connect Example.");
Connection conn = null;
try {
String driver = "net.sourceforge.jtds.jdbc.Driver";
Class.forName(driver).newInstance();
//test = com.microsoft.sqlserver.jdbc.SQLServerDriver.class;
String connString = "jdbc:jtds:sqlserver://server_ip_address :1433/DBNAME;encrypt=fasle;user=xxxxxxxxx;password=xxxxxxxx;instance=SQLEXPRESS;";
String username = "xxxxxx";
String password = "xxxxxxxxxx";
conn = DriverManager.getConnection(connString,username,password);
Log.w("Connection","open");
Statement stmt = conn.createStatement();
ResultSet reset = stmt.executeQuery("select * from TableName");

//Print the data to the console
while(reset.next()){
Log.w("Data:",reset.getString(3));
//              Log.w("Data",reset.getString(2));
}
conn.close();

} catch (Exception e)
{
Log.w("Error connection","" + e.getMessage());
}
}

4. You will find more about parameter passing here in connection string  http://jtds.sourceforge.net/doc.html .

About these ads

39 Responses to “How to connect and access SQL Database server from Android app??”

  1. Ricardo Gallwas Says:

    A big thank you for your article post.Much thanks again. Keep writing.

  2. Jere Salzmann Says:

    Hello Web Admin, I noticed that your On-Page SEO is not that great, for one you do not use all three H tags in your post, also I notice that you are not using bold or italics properly in your SEO optimization. On-Page SEO means more now than ever since the new Google update: Panda. No longer are backlinks and simply pinging or sending out a RSS feed the key to getting Google PageRank or Alexa Rankings, You now NEED On-Page SEO. So what is good On-Page SEO?First your keyword must appear in the title.Then it must appear in the URL.You have to optimize your keyword and make sure that it has a nice keyword density of 3-5% in your article with relevant LSI (Latent Semantic Indexing). Then you should spread all H1,H2,H3 tags in your article.Your Keyword should appear in your first paragraph and in the last sentence of the page. You should have relevant usage of Bold and italics of your keyword.There should be one internal link to a page on your blog and you should have one image with an alt tag that has your keyword….wait there’s even more Now what if i told you there was a simple WordPress plugin that does all the On-Page SEO, and automatically for you? That’s right AUTOMATICALLY, just watch this 4minute video for more information at. WordPress Seo Plugin

  3. jerry Says:

    Oh sorry in this connection, which network that you connect to each other?
    wireless or something else…

    • amitku Says:

      I think wireless/other-connection will not vary. My database server machine was on the private network(Intranet) and my android device and emulator was connected on that network.

      • jerry Says:

        Yes thank you!

        Excuse me sir ! When i follow from your code on Eclipse and run with Android Emulator in the same machine, why it show the message in log that : Error connection Unable to get information from SQL Server : 169.254.91.62.
        About the server_ip_address i try to get from (TCP/IP in SQL Server configuration manager), (Local Area Connection)…. What the problem?

        SQL Server 2008 (MSSQLSERVER)
        Database Name : MyDB
        User : sa
        Password : 123

        Best regard.
        Jerry

      • amitku Says:

        I feel glad to help you! Please try to access any site from Android Emulator that is hosted in your local machine. If this can be accessed then SQL Server can be accessed (in your case there may be SQL Server authentication/configuration problem, hints: SQLEXPRESS instead of MSSQLSERVER, // or \\, I know little about Database Server), otherwise I guess SQL Server in same machine can’t be accessed from Emulator.
        You are most welcome.

  4. jerry Says:

    Yes sir ! Thank you so much for your help. I’m really admire of you… and I think u are my guide.
    Next time if I have some problem again, Can I ask you?
    Sorry that I bother you a lot…

    Best regard.
    Jerry

  5. Fabio Says:

    Amitku, how’re you?
    I’m development a software will access MSSQL by TCP/IP. Is your java code enough to do that? I ask it because I tried to run in the Android emulator and I didn’t get it to work. It show the same message from Jerry.

    PS: sorry for my bad english. If you don’t understand me, please talk to me, ok?

    Thank you so much.

    • amitku Says:

      As I tested this code with SQL Server 2008 running in a different machine on the Intranet, I think this code will work. Follow “Ricardo Gallwas” comment.

      Thanks for following this post.

    • amitku Says:

      But for what kind of scenario you want to access Database server? My thinking is that if you need to access Database server for grabbing data from your phone/tablet application it will be better to create web-service(php,ruby on rails, asp.net, J2EE) to access database and query the data or save the data by web service into your database by URL/http request from your Android application and then do whatever you want in your application with that data.
      I do that for an Android application which is also a live web application.
      I apology for any misleading suggestion. Thanks

  6. anand Says:

    am developing a android mobile app and in that i want to access and insert the text values into the MS sql sever database.can u give me the code for that.Thanks in advance…

    For DB Connection :

    Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
    con=DriverManager.getConnection(“Jdbc:Odbc:Driver={SQL Server};Database=”+db_database+”;Server=”+db_server+”,”+db_port+”;”,db_username,db_password);
    Database : CRLocator
    Port : 49162
    Username : crlocator
    pwd : crlocator

  7. Percy Says:

    Hi there. first of all i gotta say congrats for your article, it came in handy. However, i found a problem when running it. It throws the follwing exception:
    Charset 0x0904D0002A/Cp850 is not supported by the JVM.
    I googled it and found that charsets.jar is missing in my Android’s JVM. now the question is how do i install this jar in my android? I tried adding this jar to my android project and compiling it but i still get the same exception when running it in my android phone.

    Thanks in advance :)

  8. Sham Says:

    I have done the Steps 1 & 2
    Can you explain at which location i need to call this step:3. Actually this code is not invoked by the project.

    regards
    Sham

  9. Kin Says:

    From the above link http://jtds.sourceforge.net/, I just can find JDBC driver in Wondow version. Where can i find the linux version? Thanks anyway.

  10. Mohit kumawat Says:

    hi amitku:

    Can u help me for the MYSQL database calling in an android application?
    Please tell me there is any way to call database table into the android device, and i don’t want use any middle ware
    for that, direct connection with a database.
    if it is possible then tell me, it will help me for my project.

  11. srinivasan sampath Says:

    sir i am having one doubt i am using your coding to connect sql sever but i am getting an error while running application in log i am getting unable to get information from sql server

  12. rakesh Says:

    thank you so much for this tutorials

  13. Alvi Says:

    Hello I am getting an error Classnotfoundexception. can you plz tell me how to resolve this issue

  14. Mohammad Says:

    Hey Amitku.

    Thanks for the wonderful article but dude Im stuck.
    can just provide a zip file of your project
    so I can go through.

    Becz for me my Logcat
    all is saying ERROR CONNECTION

    “05-21 12:47:07.462: E/Error connection(403): net.sourceforge.jtds.jdbc.Driver”

    Don’t have any idea.
    Cheers man

  15. rajesh Says:

    Thank you for give this connectivity code.
    thank you very much


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: