Example usage for android.database.sqlite SQLiteStatement close

List of usage examples for android.database.sqlite SQLiteStatement close

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteStatement close.

Prototype

public void close() 

Source Link

Document

Releases a reference to the object, closing the object if the last reference was released.

Usage

From source file:io.requery.android.database.sqlite.SQLiteDatabase.java

private int executeSql(String sql, Object[] bindArgs) throws SQLException {
    acquireReference();//from  www .  j a va  2 s  .c om
    try {
        SQLiteStatement statement = new SQLiteStatement(this, sql, bindArgs);
        try {
            return statement.executeUpdateDelete();
        } finally {
            statement.close();
        }
    } finally {
        releaseReference();
    }
}

From source file:io.requery.android.database.sqlite.SQLiteDatabase.java

/**
 * General method for inserting a row into the database.
 *
 * @param table the table to insert the row into
 * @param nullColumnHack optional; may be <code>null</code>.
 *            SQL doesn't allow inserting a completely empty row without
 *            naming at least one column name.  If your provided <code>initialValues</code> is
 *            empty, no column names are known and an empty row can't be inserted.
 *            If not set to null, the <code>nullColumnHack</code> parameter
 *            provides the name of nullable column name to explicitly insert a NULL into
 *            in the case where your <code>initialValues</code> is empty.
 * @param initialValues this map contains the initial column values for the
 *            row. The keys should be the column names and the values the
 *            column values//w ww .  ja v a  2  s.  co  m
 * @param conflictAlgorithm for insert conflict resolver
 * @return the row ID of the newly inserted row
 * OR the primary key of the existing row if the input param 'conflictAlgorithm' =
 * {@link #CONFLICT_IGNORE}
 * OR -1 if any error
 */
@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
public long insertWithOnConflict(String table, String nullColumnHack, ContentValues initialValues,
        @ConflictAlgorithm int conflictAlgorithm) {
    acquireReference();
    try {
        StringBuilder sql = new StringBuilder();
        sql.append("INSERT");
        sql.append(CONFLICT_VALUES[conflictAlgorithm]);
        sql.append(" INTO ");
        sql.append(table);
        sql.append('(');

        Object[] bindArgs = null;
        int size = (initialValues != null && initialValues.size() > 0) ? initialValues.size() : 0;
        if (size > 0) {
            bindArgs = new Object[size];
            int i = 0;
            for (Map.Entry<String, Object> entry : initialValues.valueSet()) {
                sql.append((i > 0) ? "," : "");
                sql.append(entry.getKey());
                bindArgs[i++] = entry.getValue();
            }
            sql.append(')');
            sql.append(" VALUES (");
            for (i = 0; i < size; i++) {
                sql.append((i > 0) ? ",?" : "?");
            }
        } else {
            sql.append(nullColumnHack + ") VALUES (NULL");
        }
        sql.append(')');

        SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
        try {
            return statement.executeInsert();
        } finally {
            statement.close();
        }
    } finally {
        releaseReference();
    }
}

From source file:io.requery.android.database.sqlite.SQLiteDatabase.java

/**
 * Convenience method for updating rows in the database.
 *
 * @param table the table to update in//from w w w . ja  v  a 2 s .  c  om
 * @param values a map from column names to new column values. null is a
 *            valid value that will be translated to NULL.
 * @param whereClause the optional WHERE clause to apply when updating.
 *            Passing null will update all rows.
 * @param whereArgs You may include ?s in the where clause, which
 *            will be replaced by the values from whereArgs. The values
 *            will be bound as Strings.
 * @param conflictAlgorithm for update conflict resolver
 * @return the number of rows affected
 */
public int updateWithOnConflict(String table, ContentValues values, String whereClause, String[] whereArgs,
        @ConflictAlgorithm int conflictAlgorithm) {
    if (values == null || values.size() == 0) {
        throw new IllegalArgumentException("Empty values");
    }

    acquireReference();
    try {
        StringBuilder sql = new StringBuilder(120);
        sql.append("UPDATE ");
        sql.append(CONFLICT_VALUES[conflictAlgorithm]);
        sql.append(table);
        sql.append(" SET ");

        // move all bind args to one array
        int setValuesSize = values.size();
        int bindArgsSize = (whereArgs == null) ? setValuesSize : (setValuesSize + whereArgs.length);
        Object[] bindArgs = new Object[bindArgsSize];
        int i = 0;
        for (Map.Entry<String, Object> entry : values.valueSet()) {
            sql.append((i > 0) ? "," : "");
            sql.append(entry.getKey());
            bindArgs[i++] = entry.getValue();
            sql.append("=?");
        }
        if (whereArgs != null) {
            for (i = setValuesSize; i < bindArgsSize; i++) {
                bindArgs[i] = whereArgs[i - setValuesSize];
            }
        }
        if (!TextUtils.isEmpty(whereClause)) {
            sql.append(" WHERE ");
            sql.append(whereClause);
        }

        SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
        try {
            return statement.executeUpdateDelete();
        } finally {
            statement.close();
        }
    } finally {
        releaseReference();
    }
}

From source file:com.ichi2.anki.SyncClient.java

private void deleteMedia(JSONArray ids) {
    Log.i(AnkiDroidApp.TAG, "deleteMedia");
    AnkiDb ankiDB = AnkiDatabaseManager.getDatabase(mDeck.getDeckPath());

    String idsString = Utils.ids2str(ids);

    // Get filenames
    ArrayList<String> files = ankiDB.queryColumn(String.class,
            "SELECT filename FROM media WHERE id IN " + idsString, 0);

    // Note the media to delete (Insert the media to delete into mediaDeleted)
    double now = Utils.now();
    String sqlInsert = "INSERT INTO mediaDeleted SELECT id, " + String.format(Utils.ENGLISH_LOCALE, "%f", now)
            + " FROM media WHERE media.id = ?";
    SQLiteStatement statement = ankiDB.getDatabase().compileStatement(sqlInsert);
    int len = ids.length();
    for (int i = 0; i < len; i++) {
        try {//from  w  w  w .j a  v a  2s  .c o  m
            Log.i(AnkiDroidApp.TAG, "Inserting media " + ids.getLong(i) + " into mediaDeleted");
            statement.bindLong(1, ids.getLong(i));
            statement.executeInsert();
        } catch (JSONException e) {
            Log.i(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
        }
    }
    statement.close();

    // Delete media
    Log.i(AnkiDroidApp.TAG, "Deleting media in = " + idsString);
    ankiDB.getDatabase().execSQL("DELETE FROM media WHERE id IN " + idsString);
}

From source file:com.ichi2.anki.SyncClient.java

private void updateDeck(JSONObject deckPayload) {
    try {//ww w .  j  a  va 2s. com
        JSONArray meta = deckPayload.getJSONArray("meta");

        // Update meta information
        String sqlMeta = "INSERT OR REPLACE INTO deckVars (key, value) VALUES(?,?)";
        SQLiteStatement statement = AnkiDatabaseManager.getDatabase(mDeck.getDeckPath()).getDatabase()
                .compileStatement(sqlMeta);
        int lenMeta = meta.length();
        for (int i = 0; i < lenMeta; i++) {
            JSONArray deckVar = meta.getJSONArray(i);

            // key
            statement.bindString(1, deckVar.getString(0));
            // value
            statement.bindString(2, deckVar.getString(1));

            statement.execute();
        }
        statement.close();

        // Update deck
        mDeck.updateFromJson(deckPayload);
    } catch (JSONException e) {
        Log.i(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
    }

}

From source file:io.requery.android.database.sqlite.SQLiteDatabase.java

/**
 * Convenience method for deleting rows in the database.
 *
 * @param table the table to delete from
 * @param whereClause the optional WHERE clause to apply when deleting.
 *            Passing null will delete all rows.
 * @param whereArgs You may include ?s in the where clause, which
 *            will be replaced by the values from whereArgs. The values
 *            will be bound as Strings.//from  w  w  w .j ava  2  s. c  o  m
 * @return the number of rows affected if a whereClause is passed in, 0
 *         otherwise. To remove all rows and get a count pass "1" as the
 *         whereClause.
 */
public int delete(String table, String whereClause, String[] whereArgs) {
    acquireReference();
    try {
        SQLiteStatement statement = new SQLiteStatement(this,
                "DELETE FROM " + table + (!TextUtils.isEmpty(whereClause) ? " WHERE " + whereClause : ""),
                whereArgs);
        try {
            return statement.executeUpdateDelete();
        } finally {
            statement.close();
        }
    } finally {
        releaseReference();
    }
}

From source file:com.gimranov.zandy.app.task.APIRequest.java

/**
 * Saves the APIRequest's basic info to the database. Does not maintain handler information.
 * @param db//  ww  w  .  j  a v a2 s .  co  m
 */
public void save(Database db) {
    try {
        Log.d(TAG, "Saving APIRequest to database: " + uuid + " " + query);
        SQLiteStatement insert = db.compileStatement("insert or replace into apirequests "
                + "(uuid, type, query, key, method, disposition, if_match, update_key, update_type, "
                + "created, last_attempt, status, body)" + " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)");
        // Why, oh why does bind* use 1-based indexing? And cur.get* uses 0-based!
        insert.bindString(1, uuid);
        insert.bindLong(2, (long) type);

        String createdUnix = Long.toString(created.getTime());
        String lastAttemptUnix;
        if (lastAttempt == null)
            lastAttemptUnix = null;
        else
            lastAttemptUnix = Long.toString(lastAttempt.getTime());
        String status = Integer.toString(this.status);

        // Iterate through null-allowed strings and bind them
        String[] strings = { query, key, method, disposition, ifMatch, updateKey, updateType, createdUnix,
                lastAttemptUnix, status, body };
        for (int i = 0; i < strings.length; i++) {
            Log.d(TAG, (3 + i) + ":" + strings[i]);
            if (strings[i] == null)
                insert.bindNull(3 + i);
            else
                insert.bindString(3 + i, strings[i]);
        }

        insert.executeInsert();
        insert.clearBindings();
        insert.close();
    } catch (SQLiteException e) {
        Log.e(TAG, "Exception compiling or running insert statement", e);
        throw e;
    }
}

From source file:com.ichi2.anki.SyncClient.java

private void updateSources(JSONArray sources) {
    String sql = "INSERT OR REPLACE INTO sources VALUES(?,?,?,?,?)";
    SQLiteStatement statement = AnkiDatabaseManager.getDatabase(mDeck.getDeckPath()).getDatabase()
            .compileStatement(sql);//from w  w w.  j  a  v a 2s  .  c o m
    int len = sources.length();
    for (int i = 0; i < len; i++) {
        try {
            JSONArray source = sources.getJSONArray(i);
            statement.bindLong(1, source.getLong(0));
            statement.bindString(2, source.getString(1));
            statement.bindDouble(3, source.getDouble(2));
            statement.bindDouble(4, source.getDouble(3));
            statement.bindString(5, source.getString(4));
            statement.execute();
        } catch (JSONException e) {
            Log.i(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
        }
    }
    statement.close();
}

From source file:io.requery.android.database.sqlite.SQLiteDatabase.java

/**
 * Runs 'pragma integrity_check' on the given database (and all the attached databases)
 * and returns true if the given database (and all its attached databases) pass integrity_check,
 * false otherwise.// w  w w  .  j  ava 2  s.  c om
 *<p>
 * If the result is false, then this method logs the errors reported by the integrity_check
 * command execution.
 *<p>
 * Note that 'pragma integrity_check' on a database can take a long time.
 *
 * @return true if the given database (and all its attached databases) pass integrity_check,
 * false otherwise.
 */
public boolean isDatabaseIntegrityOk() {
    acquireReference();
    try {
        List<Pair<String, String>> attachedDbs;
        try {
            attachedDbs = getAttachedDbs();
            if (attachedDbs == null) {
                throw new IllegalStateException("databaselist for: " + getPath() + " couldn't "
                        + "be retrieved. probably because the database is closed");
            }
        } catch (SQLiteException e) {
            // can't get attachedDb list. do integrity check on the main database
            attachedDbs = new ArrayList<>();
            attachedDbs.add(new Pair<>("main", getPath()));
        }

        for (Pair<String, String> p : attachedDbs) {
            SQLiteStatement prog = null;
            try {
                prog = compileStatement("PRAGMA " + p.first + ".integrity_check(1);");
                String rslt = prog.simpleQueryForString();
                if (!rslt.equalsIgnoreCase("ok")) {
                    // integrity_checker failed on main or attached databases
                    Log.e(TAG, "PRAGMA integrity_check on " + p.second + " returned: " + rslt);
                    return false;
                }
            } finally {
                if (prog != null)
                    prog.close();
            }
        }
    } finally {
        releaseReference();
    }
    return true;
}

From source file:de.stadtrallye.rallyesoft.model.chat.Chatroom.java

/**
 * Save ChatEntries to DB//from   w  w  w  .  j  av  a  2 s . c  o m
 *
 * @param entries All entries that have a higher chatID than this.newestID will be saved to DB
 */
private void saveChats(List<ChatEntry> entries) {
    //KEY_ID, KEY_TIME, FOREIGN_GROUP, FOREIGN_USER, KEY_MESSAGE, KEY_PICTURE, FOREIGN_ROOM
    SQLiteStatement s = getDb().compileStatement("INSERT INTO " + DatabaseHelper.Chats.TABLE + " ("
            + DatabaseHelper.strStr(DatabaseHelper.Chats.COLS) + ") VALUES (?, ?, ?, ?, ?, ?, " + chatroomID
            + ")");

    int chatId;
    List<ChatEntry> update = new ArrayList<>();

    stateLock.writeLock().lock();
    try {
        ChatEntry c;
        for (Iterator<ChatEntry> i = entries.iterator(); i.hasNext();) {
            c = i.next();

            if (c.chatID <= newestID) { // Already seen this entry
                if (c.timestamp > lastUpdateTime) { // Entry has changed since last seen
                    update.add(c);
                }
                i.remove(); // ignore
                continue;

            }

            try {
                //            Log.d(THIS, "Inserted "+c+" in Messages");

                s.bindLong(1, c.chatID);
                s.bindLong(2, c.timestamp);
                s.bindLong(3, c.groupID);
                s.bindLong(4, c.userID);
                s.bindString(5, c.message);

                if (c.pictureHash != null)
                    s.bindString(6, c.pictureHash);
                else
                    s.bindNull(6);

                chatId = (int) s.executeInsert();

                //            Log.d(THIS, "Inserted "+c+" in Chats");

                if (chatId != c.chatID)
                    throw new SQLDataException();

            } catch (Exception e) {
                Log.e(THIS, "Single Insert failed", e);
            }
        }

        if (entries.size() > 0) {
            ChatEntry last = entries.get(entries.size() - 1);

            setLast(last.timestamp, last.chatID);
        }

        Log.i(THIS, "Received " + entries.size() + " new Chats in Chatroom " + chatroomID + " since "
                + lastUpdateTime);

    } catch (Exception e) {
        Log.e(THIS, "All Inserts failed", e);
    } finally {
        stateLock.writeLock().unlock();
        s.close();
    }

    if (update.size() > 0) {
        Log.w(THIS, "Chat entries were changed on Server: " + update);
        for (ChatEntry c : update) {
            editChat(c);
        }
    }

    checkForNewUsers();
    checkForNewGroups();

    notifyChatsChanged();
}