Example usage for android.database.sqlite SQLiteDatabase execSQL

List of usage examples for android.database.sqlite SQLiteDatabase execSQL

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteDatabase execSQL.

Prototype

public void execSQL(String sql) throws SQLException 

Source Link

Document

Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.

Usage

From source file:org.mitre.svmp.common.DatabaseHandler.java

private void addTableColumn(int tableID, int colNum, String defaultVal, SQLiteDatabase db) {
    String query = String.format("ALTER TABLE %s ADD COLUMN %s %s DEFAULT %s", Tables[tableID], // table name
            TableColumns[tableID][colNum][0], // column name
            TableColumns[tableID][colNum][1], // column type
            defaultVal);/*  www  . j a  v a 2 s . com*/
    // try to create the table with the constructed query
    try {
        db.execSQL(query);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.kontalk.provider.UsersProvider.java

private void endTransaction(SQLiteDatabase db, boolean success) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB)
        db.endTransaction();//  w  w  w  .j  a v  a2 s .  c o m
    else
        db.execSQL(success ? "COMMIT" : "ROLLBACK");
}

From source file:com.example.week04.GcmIntentService.java

private void getArticleInBackground(final String keyword) {
    new AsyncTask<Void, Void, Void>() {
        private String resultMessage = "";

        @Override/*from  ww  w.j a v  a2s . c  o m*/
        protected Void doInBackground(Void... params) {
            String serverURL = new Settings().getServerURL();
            String URL = serverURL + "getArticle/" + keyword;
            DefaultHttpClient client = new DefaultHttpClient();
            String result;
            try {
                // Make connection to server.
                Log.i("Connection", "Make connection to server");
                HttpParams connectionParams = client.getParams();
                HttpConnectionParams.setConnectionTimeout(connectionParams, 5000);
                HttpConnectionParams.setSoTimeout(connectionParams, 5000);
                HttpGet httpGet = new HttpGet(URL);

                // Get response and parse entity.
                Log.i("Connection", "Get response and parse entity.");
                HttpResponse responsePost = client.execute(httpGet);
                HttpEntity resEntity = responsePost.getEntity();

                // Parse result to string.
                Log.i("Connection", "Parse result to string.");
                result = EntityUtils.toString(resEntity);
                result = result.replaceAll("'|&lt;|&quot;|&gt;", "''");
            } catch (Exception e) {
                e.printStackTrace();
                Log.i("Connection", "Some error in server!");
                result = "";
            }

            client.getConnectionManager().shutdown(); // Disconnect.

            if (!result.isEmpty()) {
                try {
                    JSONArray articleArray = new JSONArray(result);
                    int arrayLength = articleArray.length();
                    int updatedRow = 0;

                    DBHelper mHelper = new DBHelper(getApplicationContext());
                    SQLiteDatabase db = mHelper.getWritableDatabase();
                    for (int i = 0; i < arrayLength; i++) {
                        JSONObject articleObject = articleArray.getJSONObject(i);
                        String title = articleObject.getString("Title");
                        String link = articleObject.getString("Link");
                        String date = articleObject.getString("Date");
                        String news = articleObject.getString("News");
                        String content = articleObject.getString("Head");
                        String query = "INSERT INTO ARTICLES(KEYWORD, TITLE, NEWS, DATE, CONTENT, LINK) VALUES('"
                                + keyword + "', '" + title + "', '" + news + "', '" + date + "', '" + content
                                + "', '" + link + "');";
                        try {
                            updatedRow++;
                            db.execSQL(query);
                        } catch (SQLException e) {
                            updatedRow--;
                            Log.i("SQL inserting", "SQL exception in " + i + "th row : duplicated?");
                        }

                    }

                    String thisTime = getThisTime();
                    String query = "UPDATE KEYWORDS SET LASTUPDATE = '" + thisTime + "' WHERE KEYWORD = '"
                            + keyword + "';";
                    db.execSQL(query);

                    mHelper.close();

                    if (updatedRow > 0) {
                        resultMessage = "Article loading complete!";
                        sendNotification(
                                "'" + keyword + "'    " + updatedRow + " !");
                    } else {
                        resultMessage = "Loading complete - No fresh news.";
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    resultMessage = "Error in article loading - problem in JSONArray?";
                }
            } else {
                resultMessage = "Error in receiving articles!";
            }
            Log.i("JSON parsing", resultMessage);
            return null;
        }
    }.execute(null, null, null);
}

From source file:com.dm.wallpaper.board.databases.Database.java

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_TABLE_CATEGORY = "CREATE TABLE " + TABLE_CATEGORIES + "(" + KEY_ID
            + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + KEY_NAME + " TEXT NOT NULL," + KEY_THUMB_URL
            + " TEXT, " + KEY_SELECTED + " INTEGER DEFAULT 1," + KEY_MUZEI_SELECTED + " INTEGER DEFAULT 1, "
            + "UNIQUE (" + KEY_NAME + ") ON CONFLICT REPLACE)";
    String CREATE_TABLE_WALLPAPER = "CREATE TABLE IF NOT EXISTS " + TABLE_WALLPAPERS + "(" + KEY_ID
            + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + KEY_NAME + " TEXT NOT NULL, " + KEY_AUTHOR
            + " TEXT NOT NULL, " + KEY_THUMB_URL + " TEXT NOT NULL, " + KEY_URL + " TEXT NOT NULL, "
            + KEY_CATEGORY + " TEXT NOT NULL," + KEY_FAVORITE + " INTEGER DEFAULT 0," + KEY_ADDED_ON
            + " TEXT NOT NULL, " + "UNIQUE (" + KEY_URL + ") ON CONFLICT REPLACE)";
    db.execSQL(CREATE_TABLE_CATEGORY);
    db.execSQL(CREATE_TABLE_WALLPAPER);/*from w w w.j  a v  a 2  s  .  c o m*/
}

From source file:org.kontalk.provider.UsersProvider.java

/** Commits the offline table to the online table. */
private void commit() {
    SQLiteDatabase db = dbHelper.getWritableDatabase();

    // begin transaction
    beginTransaction(db);/*  w  w  w .  j a v  a2s. c o m*/
    boolean success = false;

    try {
        // copy contents from offline
        db.execSQL("DELETE FROM " + TABLE_USERS);
        db.execSQL("INSERT INTO " + TABLE_USERS + " SELECT * FROM " + TABLE_USERS_OFFLINE);
        success = setTransactionSuccessful(db);
    } catch (SQLException e) {
        // ops :)
        Log.i(SyncAdapter.TAG, "users table commit failed - already committed?", e);
    } finally {
        endTransaction(db, success);
        // time to invalidate contacts cache
        Contact.invalidate();
    }
}

From source file:com.snt.bt.recon.database.DBHandler.java

public <T> void updateSyncStatus(Class<T> cl, JSONObject obj)
        throws InstantiationException, IllegalAccessException, JSONException {
    T inst = cl.newInstance();/*from ww  w  . java  2s  .  c om*/
    SQLiteDatabase database = this.getWritableDatabase();
    String updateQuery = "";

    if (inst instanceof Trip) {
        if (obj.get("status").toString().equals("yes"))
            database.delete(TABLE_TRIPS,
                    KEY_SESSION_ID + "=" + "'" + UUID.fromString(obj.get("session_id").toString()) + "'", null);
        else {
            updateQuery = "UPDATE " + TABLE_TRIPS + " set " + KEY_UPLOAD_STATUS + " = '"
                    + obj.get("status").toString() + "' where " + KEY_SESSION_ID + "=" + "'"
                    + UUID.fromString(obj.get("session_id").toString()) + "'";
            database.execSQL(updateQuery);
        }
    } else if (inst instanceof GPSLocation)
        if (obj.get("status").toString().equals("yes"))
            database.delete(TABLE_LOCATIONS,
                    KEY_LOCATION_ID + "=" + "'" + UUID.fromString(obj.get("location_id").toString()) + "'",
                    null);
        else {
            updateQuery = "UPDATE " + TABLE_LOCATIONS + " set " + KEY_UPLOAD_STATUS + " = '"
                    + obj.get("status").toString() + "' where " + KEY_LOCATION_ID + "=" + "'"
                    + UUID.fromString(obj.get("location_id").toString()) + "'";
            database.execSQL(updateQuery);
        }
    else if (inst instanceof BluetoothClassicEntry)
        if (obj.get("status").toString().equals("yes"))
            database.delete(TABLE_BC, "id=" + obj.getInt("id") + "", null);
        else {
            updateQuery = "UPDATE " + TABLE_BC + " set " + KEY_UPLOAD_STATUS + " = '"
                    + obj.get("status").toString() + "' where id=" + obj.getInt("id") + "";
            database.execSQL(updateQuery);
        }
    else if (inst instanceof BluetoothLowEnergyEntry)
        if (obj.get("status").toString().equals("yes"))
            database.delete(TABLE_BLE, "id=" + obj.getInt("id") + "", null);
        else {
            updateQuery = "UPDATE " + TABLE_BLE + " set " + KEY_UPLOAD_STATUS + " = '"
                    + obj.get("status").toString() + "' where id=" + obj.getInt("id") + "";
            database.execSQL(updateQuery);
        }

    //Log.d("DatabaseTest", updateQuery);
    database.close();
}

From source file:org.kontalk.provider.UsersProvider.java

@TargetApi(android.os.Build.VERSION_CODES.HONEYCOMB)
private void beginTransaction(SQLiteDatabase db) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB)
        db.beginTransactionNonExclusive();
    else//from   www .  j a  v a 2 s .  c om
        // this is because API < 11 doesn't have beginTransactionNonExclusive()
        db.execSQL("BEGIN IMMEDIATE");
}

From source file:org.mitre.svmp.common.DatabaseHandler.java

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    switch (oldVersion) {
    case 1://from w  w w .  j  ava 2s  . c o m
        // changed Connections table, recreate it
        recreateTable(TABLE_CONNECTIONS, db);
    case 2:
        addTableColumn(TABLE_CONNECTIONS, 6, "''", db);
        addTableColumn(TABLE_CONNECTIONS, 7, "0", db);
    case 3:
        // changed auth types, now the IDs begin with 1, not 0
        db.execSQL("UPDATE Connections SET AuthType=1 WHERE AuthType=0;");
    case 4:
        // added measurement info and performance data tables, no need to change existing info
        createTable(TABLE_MEASUREMENT_INFO, db);
        createTable(TABLE_PERFORMANCE_DATA, db);
    case 5:
        addTableColumn(TABLE_CONNECTIONS, 8, "''", db); // SessionToken column added
    case 6:
        addTableColumn(TABLE_CONNECTIONS, 9, "''", db); // CertificateAlias column added
    case 7:
        // changed encryption types, removed SSL/untrusted, now we just have SSL
        db.execSQL("UPDATE Connections SET EncryptionType=1 WHERE EncryptionType=2;");
    case 8:
        // changed session handling, now the client is aware when a session token is not valid
        db.execSQL("UPDATE Connections SET SessionToken='';"); // clear out all existing session tokens
        addTableColumn(TABLE_CONNECTIONS, 10, "0", db); // SessionExpires column added
        addTableColumn(TABLE_CONNECTIONS, 11, "0", db); // SessionGracePeriod column added
        addTableColumn(TABLE_CONNECTIONS, 12, "0", db); // LastDisconnected column added
    case 9:
        // added Apps table, no need to change existing data
        createTable(TABLE_APPS, db);
    case 10:
        // we don't use the Connections table's SessionGracePeriod column anymore, but there's no way to drop it
    case 11:
        // we don't use the Connections table's LastDisconnected column anymore, but there's no way to drop it
        // added session info columns
        addTableColumn(TABLE_CONNECTIONS, 13, "''", db); // SessionHost column added
        addTableColumn(TABLE_CONNECTIONS, 14, "''", db); // SessionPort column added
        addTableColumn(TABLE_CONNECTIONS, 15, "''", db); // SessionWebrtc column added
        // clear any existing session info
        ContentValues values = new ContentValues();
        values.put("SessionToken", "");
        // attempt update
        try {
            db.update(Tables[TABLE_CONNECTIONS], values, null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        updateRecord(TABLE_CONNECTIONS, values, null);
    default:
        break;
    }
}

From source file:project.cs.netinfservice.database.IODatabase.java

/**
 * Called when the database is created for the first time. This is where the creation of
 * tables and the initial population of the tables should happen.
 * //from   ww w .j  ava 2s  . c o  m
 * @param db
 *     The SQLite database.
 */
@Override
public void onCreate(SQLiteDatabase db) {
    String createIoTable = "CREATE TABLE " + TABLE_IO + "(" + KEY_HASH + " TEXT PRIMARY KEY,"
            + KEY_HASH_ALGORITHM + " TEXT NOT NULL, " + KEY_CONTENT_TYPE + " TEXT NOT NULL, " + KEY_FILEPATH
            + " TEXT NOT NULL, " + KEY_FILE_SIZE + " REAL NOT NULL CHECK(" + KEY_FILE_SIZE + " > 0.0))";

    String createUrlTable = "CREATE TABLE " + TABLE_URL + "(" + KEY_HASH + " TEXT NOT NULL, " + KEY_URL
            + " TEXT NOT NULL, " + "CONSTRAINT primarykey PRIMARY KEY " + "( " + KEY_HASH + ", " + KEY_URL
            + "), " + "FOREIGN KEY (" + KEY_HASH + ") " + "REFERENCES " + TABLE_IO + " ( " + KEY_HASH + ") "
            + "ON DELETE CASCADE )";

    db.execSQL(createIoTable);
    db.execSQL(createUrlTable);
}

From source file:com.dm.material.dashboard.candybar.databases.Database.java

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_TABLE_REQUEST = "CREATE TABLE IF NOT EXISTS " + TABLE_REQUEST + "(" + KEY_ID
            + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + KEY_NAME + " TEXT NOT NULL, " + KEY_ACTIVITY
            + " TEXT NOT NULL, " + KEY_REQUESTED_ON + " DATETIME DEFAULT CURRENT_TIMESTAMP" + ")";
    String CREATE_TABLE_PREMIUM_REQUEST = "CREATE TABLE IF NOT EXISTS " + TABLE_PREMIUM_REQUEST + "(" + KEY_ID
            + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + KEY_ORDER_ID + " TEXT NOT NULL, "
            + KEY_PRODUCT_ID + " TEXT NOT NULL, " + KEY_REQUEST + " TEXT NOT NULL, " + KEY_REQUESTED_ON
            + " DATETIME DEFAULT CURRENT_TIMESTAMP" + ")";
    String CREATE_TABLE_WALLPAPER = "CREATE TABLE IF NOT EXISTS " + TABLE_WALLPAPERS + "(" + KEY_ID
            + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + KEY_NAME + " TEXT NOT NULL, " + KEY_AUTHOR
            + " TEXT NOT NULL, " + KEY_URL + " TEXT NOT NULL, " + KEY_THUMB_URL + " TEXT NOT NULL, "
            + KEY_ADDED_ON + " DATETIME DEFAULT CURRENT_TIMESTAMP" + ")";
    db.execSQL(CREATE_TABLE_REQUEST);
    db.execSQL(CREATE_TABLE_PREMIUM_REQUEST);
    db.execSQL(CREATE_TABLE_WALLPAPER);//from w  ww  . j  a  v a  2  s. co  m
}