Exec SQL on SQLServer database - Android Database

Android examples for Database:SQL Query

Description

Exec SQL on SQLServer database

Demo Code


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import android.os.Bundle;
import android.os.Message;
import android.widget.TextView;

public class Main{
    final static String user = "sa";
    final static String pwd = "";
    final static String db = "dbName";
    public static boolean ExecSQL(String sql) {
        try {//from  w  w  w .ja v  a 2  s  .  c  o m
            Connection conn = null;

            conn = getSQLConnection();
            if (conn == null)
                return false;
            Statement stmt = conn.createStatement();// 
            stmt.execute(sql);
            stmt.close();
            conn.close();
            return true;
        } catch (SQLException e) {
            e.printStackTrace();

        }
        return false;
    }
    public static Connection getSQLConnection() {
        Connection con = null;
        try {
            if (!LoginActivity.TestConnect())
                return null;
            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            DriverManager.setLoginTimeout(1);
            con = DriverManager.getConnection("jdbc:jtds:sqlserver://"
                    + LoginActivity.strServerIP + ":1433/" + db
                    + ";charset=utf8", user, pwd);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }
}

Related Tutorials