Showing posts with label How to connect and access SQL Database server from Android app??. Show all posts
Showing posts with label How to connect and access SQL Database server from Android app??. Show all posts

How to connect and access SQL Database server fr

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
01import java.sql.Connection;
02import java.sql.DriverManager;
03import java.sql.ResultSet;
04import java.sql.Statement;
05
06import net.sourceforge.jtds.jdbc.*;
07
08public void query2()
09{
10Log.i("Android"," MySQL Connect Example.");
11Connection conn = null;
12try {
13String driver = "net.sourceforge.jtds.jdbc.Driver";
14Class.forName(driver).newInstance();
15//test = com.microsoft.sqlserver.jdbc.SQLServerDriver.class;
16String connString = "jdbc:jtds:sqlserver://server_ip_address:1433/DBNAME;encrypt=fasle;user=xxxxxxxxx;
                      password=xxxxxxxx;instance=SQLEXPRESS;";
17String username = "xxxxxx";
18String password = "xxxxxxxxxx";
19conn = DriverManager.getConnection(connString,username,password);
20Log.w("Connection","open");
21Statement stmt = conn.createStatement();
22ResultSet reset = stmt.executeQuery("select * from TableName");
23
24//Print the data to the console
25while(reset.next()){
26Log.w("Data:",reset.getString(3));
27//              Log.w("Data",reset.getString(2));
28}
29conn.close();
30
31catch (Exception e)
32{
33Log.w("Error connection","" + e.getMessage());
34}
35}