Connecting and inserting data from an Android App to a pre-existing MS SQL database

9.8k views Asked by At

I've created an Android application, which takes data from the user. I need the data collected (strings) to be posted to a MS SQL database.

I've looked into various resources but it wasn't of much help. I've got the IP, username, password, and the table and row where the said data needs to be inserted. I need the data inserted, when the user presses the submit button on the form page he/she was filling.

It would be great if this would work with the MS SQL database, as this is the mobile variant of the web app. I've tried to use jDTS 1.3.1, but it doesn't sync with gradle(module:app) when I add it below the testCompile.

2

There are 2 answers

1
Nidhin Kumar On
0
Hari_Haran_N_S. On

In my case, i had inserted data from Android to MSSQL. The thing is, you need to just add insert query in your connection. For Better convenience, i had attached my coding as below.

Initially give the Jtds connection.

Create a class called ConnectionClass,

public class ConnectionClass {
        String ip = "your_IP";
        String class = "net.sourceforge.jtds.jdbc.Driver";
        String db = "DB_name";
        String un = "UserName";
        String password = "SQLpassword";
        @SuppressLint("NewApi")
        public Connection CONN() {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
            Connection conn = null;
            String ConnURL = null;
            try {
                Class.forName(class);
                ConnURL = "jdbc:jtds:sqlserver://" + ip + ";" + "databaseName=" + db + ";user=" + un + ";password=" + password + ";";              
                conn = DriverManager.getConnection(ConnURL);
            } catch (SQLException se) {
                Log.e("ERROR", se.getMessage());
            } catch (ClassNotFoundException e) {
                Log.e("ERROR", e.getMessage());
            } catch (Exception e) {
                Log.e("ERROR", e.getMessage());
            }
            return conn;
        }
    }

For inserting into MSSQL,

 connectionClass = new ConnectionClass();
    try 
        {
        Connection con = connectionClass.CONN();
        String query = "INSERT INTO TableName(ColumnName) VALUES ('" + text  + "') " ;
        Statement stmt = con.createStatement();
        stmt.executeUpdate(query);
        }
    catch (SQLException se) 
        {
        Log.e("ERROR", se.getMessage());
        }

Note: I had used with stmt.executeUpdate(query), if not working, you can also use stmt.executeQuery(query)

Here, text denotes my own value but you can use anything like editText.

Hope, it helps...!!