Example usage for android.database.sqlite SQLiteStatement execute

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

Introduction

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

Prototype

public void execute() 

Source Link

Document

Execute this SQL statement, if it is not a SELECT / INSERT / DELETE / UPDATE, for example CREATE / DROP table, view, trigger, index etc.

Usage

From source file:com.mobshep.mobileshepherd.Insecure_Data_Storage.java

private void InsertData(String user, String pass) throws IOException {

    try {// w w w. j  a  va 2s  .  co m
        String path = DB_PATH + DB_NAME;
        Members = this.openOrCreateDatabase(path, MODE_PRIVATE, null);

        SQLiteStatement stmt = Members.compileStatement("INSERT INTO Members (name, password) VALUES (?,?);");
        stmt.bindString(1, user);
        stmt.bindString(2, pass);
        stmt.execute();

        Snackbar insert = Snackbar.make(findViewById(android.R.id.content), "Data Inserted!",
                Snackbar.LENGTH_LONG);
        insert.show();

        EditText username = (EditText) findViewById(R.id.etName);
        EditText password = (EditText) findViewById(R.id.etPass);

        username.setText("");
        password.setText("");

    } catch (Exception e) {
        Log.e("DB ERROR", "Error Inserting into Database");

        Snackbar error = Snackbar.make(findViewById(android.R.id.content), "Could not Insert Data.",
                Snackbar.LENGTH_LONG);
        error.show();
    }
}

From source file:com.mobshep.mobileshepherd.Insecure_Data_Storage1.java

private void InsertData(String user, String pass) throws IOException {

    try {//  www  . java2 s  . c  o m
        String path = DB_PATH + DB_NAME;
        Users = this.openOrCreateDatabase(path, MODE_PRIVATE, null);

        //get the base64 functionality
        annoyingObfuscationUtil util = new annoyingObfuscationUtil();

        SQLiteStatement stmt = Users.compileStatement("INSERT INTO Users (name, password) VALUES (?,?);");
        stmt.bindString(1, user);
        stmt.bindString(2, util.Obfuscation1(pass));
        stmt.execute();

        Snackbar insert = Snackbar.make(findViewById(android.R.id.content), "Data Inserted!",
                Snackbar.LENGTH_LONG);
        insert.show();

        EditText username = (EditText) findViewById(R.id.etName);
        EditText password = (EditText) findViewById(R.id.etPass);

        username.setText("");
        password.setText("");

    } catch (Exception e) {
        Log.e("DB ERROR", "Error Inserting into Database");

        Snackbar error = Snackbar.make(findViewById(android.R.id.content), "Could not Insert Data.",
                Snackbar.LENGTH_LONG);
        error.show();
    }
}

From source file:com.denimgroup.android.training.pandemobium.stocktrader.ManageTipsActivity.java

private void doSaveTip() {
    String symbol = etSymbol.getText().toString();
    Double targetPrice = Double.parseDouble(etTargetPrice.getText().toString());
    String reason = etReason.getText().toString();

    //   TOFIX - Read the username from the credentials.properties file

    String sql = "INSERT INTO tip (tip_creator, symbol, target_price, reason) VALUES (?, ?, ?, ?)";

    StockDatabase dbHelper = new StockDatabase(this.getApplicationContext());
    SQLiteDatabase db = dbHelper.openDatabase();
    SQLiteStatement stmt = db.compileStatement(sql);
    stmt.bindString(1, "USERNAME");
    stmt.bindString(2, symbol);//w  w  w.j a  va2  s. c o  m
    stmt.bindDouble(3, targetPrice);
    stmt.bindString(4, reason);
    stmt.execute();
    stmt.close();

    db.close();

    tvTipStatus.setText("Tip saved!");
}

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

public void addCategories(List<WallpaperJson> categories) {
    String query = "INSERT INTO " + TABLE_CATEGORIES + " (" + KEY_NAME + "," + KEY_THUMB_URL
            + ") VALUES (?,?);";
    SQLiteDatabase db = this.getWritableDatabase();
    SQLiteStatement statement = db.compileStatement(query);
    db.beginTransaction();/*  w  w  w  .  j a v a 2s.c om*/

    for (int i = 0; i < categories.size(); i++) {
        statement.clearBindings();
        statement.bindString(1, categories.get(i).name);
        statement.bindString(2, categories.get(i).thumbUrl == null ? "" : categories.get(i).thumbUrl);
        statement.execute();
    }
    db.setTransactionSuccessful();
    db.endTransaction();
    db.close();
}

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

public void addWallpapers(@NonNull List<Wallpaper> wallpapers) {
    String query = "INSERT INTO " + TABLE_WALLPAPERS + " (" + KEY_NAME + "," + KEY_AUTHOR + "," + KEY_URL + ","
            + KEY_THUMB_URL + "," + KEY_CATEGORY + "," + KEY_ADDED_ON + ") VALUES (?,?,?,?,?,?);";
    SQLiteDatabase db = this.getWritableDatabase();
    SQLiteStatement statement = db.compileStatement(query);
    db.beginTransaction();/*www.j  a v a  2  s  . c om*/

    for (int i = 0; i < wallpapers.size(); i++) {
        statement.clearBindings();
        statement.bindString(1, wallpapers.get(i).getName());
        statement.bindString(2, wallpapers.get(i).getAuthor());
        statement.bindString(3, wallpapers.get(i).getUrl());
        statement.bindString(4, wallpapers.get(i).getThumbUrl());
        statement.bindString(5, wallpapers.get(i).getCategory());
        statement.bindString(6, TimeHelper.getLongDateTime());
        statement.execute();
    }
    db.setTransactionSuccessful();
    db.endTransaction();
    db.close();
}

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

public void addWallpapers(@NonNull WallpaperJson wallpaper) {
    String query = "INSERT INTO " + TABLE_WALLPAPERS + " (" + KEY_NAME + "," + KEY_AUTHOR + "," + KEY_URL + ","
            + KEY_THUMB_URL + "," + KEY_CATEGORY + "," + KEY_ADDED_ON + ") VALUES (?,?,?,?,?,?);";
    SQLiteDatabase db = this.getWritableDatabase();
    SQLiteStatement statement = db.compileStatement(query);
    db.beginTransaction();//  ww  w. jav  a  2  s. c  o  m

    for (int i = 0; i < wallpaper.getWallpapers.size(); i++) {
        statement.clearBindings();
        statement.bindString(1, wallpaper.getWallpapers.get(i).name);
        statement.bindString(2, wallpaper.getWallpapers.get(i).author);
        statement.bindString(3, wallpaper.getWallpapers.get(i).url);
        statement.bindString(4,
                wallpaper.getWallpapers.get(i).thumbUrl == null ? wallpaper.getWallpapers.get(i).url
                        : wallpaper.getWallpapers.get(i).thumbUrl);
        statement.bindString(5, wallpaper.getWallpapers.get(i).category);
        statement.bindString(6, TimeHelper.getLongDateTime());
        statement.execute();
    }
    db.setTransactionSuccessful();
    db.endTransaction();
    db.close();
}

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

private int executeUpdateDelete(SQLiteDatabase db, SQLiteStatement stm) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
        return stm.executeUpdateDelete();
    } else {//  w w  w. ja va  2s.c  o m
        stm.execute();
        SQLiteStatement changes = db.compileStatement("SELECT changes()");
        try {
            return (int) changes.simpleQueryForLong();
        } finally {
            changes.close();
        }
    }
}

From source file:com.nolanlawson.cordova.sqlite.SQLitePlugin.java

private SQLitePLuginResult doUpdateInBackgroundAndPossiblyThrow(String sql, String[] bindArgs,
        SQLiteDatabase db) {/*from w  w w .ja v  a  2  s .c  o  m*/
    debug("\"run\" query: %s", sql);
    SQLiteStatement statement = null;
    try {
        statement = db.compileStatement(sql);
        debug("compiled statement");
        if (bindArgs != null) {
            statement.bindAllArgsAsStrings(bindArgs);
        }
        debug("bound args");
        if (isInsert(sql)) {
            debug("type: insert");
            long insertId = statement.executeInsert();
            int rowsAffected = insertId >= 0 ? 1 : 0;
            return new SQLitePLuginResult(EMPTY_ROWS, EMPTY_COLUMNS, rowsAffected, insertId, null);
        } else if (isDelete(sql) || isUpdate(sql)) {
            debug("type: update/delete");
            int rowsAffected = statement.executeUpdateDelete();
            return new SQLitePLuginResult(EMPTY_ROWS, EMPTY_COLUMNS, rowsAffected, 0, null);
        } else {
            // in this case, we don't need rowsAffected or insertId, so we can have a slight
            // perf boost by just executing the query
            debug("type: drop/create/etc.");
            statement.execute();
            return EMPTY_RESULT;
        }
    } finally {
        if (statement != null) {
            statement.close();
        }
    }
}

From source file:co.rewen.statex.StateXModule.java

/**
 * Inserts multiple (key, value) pairs. If one or more of the pairs cannot be inserted, this will
 * return StateXFailure, but all other pairs will have been inserted.
 * The insertion will replace conflicting (key, value) pairs.
 *//*  w  w  w .  ja  v a2  s.c  o  m*/
@ReactMethod
public void multiSet(final ReadableArray keyValueArray, final Callback callback) {
    if (keyValueArray.size() == 0) {
        callback.invoke(AsyncStorageErrorUtil.getInvalidKeyError(null));
        return;
    }

    new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) {
        @Override
        protected void doInBackgroundGuarded(Void... params) {
            if (!ensureDatabase()) {
                callback.invoke(AsyncStorageErrorUtil.getDBError(null));
                return;
            }

            String sql = "INSERT OR REPLACE INTO " + TABLE_STATE + " VALUES (?, ?);";
            SQLiteStatement statement = mStateXDatabaseSupplier.get().compileStatement(sql);
            WritableMap error = null;
            ArrayList<String> keys = new ArrayList<>();
            try {
                mStateXDatabaseSupplier.get().beginTransaction();
                for (int idx = 0; idx < keyValueArray.size(); idx++) {
                    if (keyValueArray.getArray(idx).size() != 2) {
                        error = AsyncStorageErrorUtil.getInvalidValueError(null);
                        break;
                    }
                    String key = keyValueArray.getArray(idx).getString(0);
                    if (key == null) {
                        error = AsyncStorageErrorUtil.getInvalidKeyError(null);
                        break;
                    }
                    String value = keyValueArray.getArray(idx).getString(1);
                    if (value == null) {
                        error = AsyncStorageErrorUtil.getInvalidValueError(null);
                        break;
                    }

                    keys.add(key);
                    statement.clearBindings();
                    statement.bindString(1, key);
                    statement.bindString(2, value);
                    statement.execute();
                }
                mStateXDatabaseSupplier.get().setTransactionSuccessful();
            } catch (Exception e) {
                FLog.w(ReactConstants.TAG, e.getMessage(), e);
                error = AsyncStorageErrorUtil.getError(null, e.getMessage());
            } finally {
                try {
                    mStateXDatabaseSupplier.get().endTransaction();
                } catch (Exception e) {
                    FLog.w(ReactConstants.TAG, e.getMessage(), e);
                    if (error == null) {
                        error = AsyncStorageErrorUtil.getError(null, e.getMessage());
                    }
                }
            }
            if (error != null) {
                callback.invoke(error);
            } else {
                callback.invoke();
                notifyStateChanged(keys);
            }
        }
    }.execute();
}

From source file:com.aquatest.dbinterface.tools.DatabaseUpdater.java

/**
 * Invoke web service to retrieve data, and then build and execute queries
 * to update local database// w w w  .j  av  a  2 s  . c om
 * 
 * @param type
 *            of rows to fetch (TYPE_ADDED, TYPE_UPDATED, TYPE_DELETED)
 * @param table
 *            table to request rows for
 * @return <code>true</code> if the method succeeds, <code>false</code> if
 *         the method fails
 * @throws ClientProtocolException
 * @throws JSONException
 *             if the data returned is not what was expected
 * @throws IOException
 */
private boolean fetchAndExecuteQueries(int type, String table)
        throws ClientProtocolException, JSONException, IOException {
    // Log.v("START", "fetchAndExecuteQueries(" + type + ", " + table +
    // ")");
    try {

        int count = 0;
        int totalCount = 1;
        int offset = 0;
        String status = "";
        JSONArray dataArray = null;
        boolean run = true;

        // determine JSON method to contact with our web service call
        String wsMethodName = "";
        switch (type) {
        case TYPE_ADDED:
            wsMethodName = AquaTestWebService.ADDED_ROWS;
            break;

        case TYPE_UPDATED:
            wsMethodName = AquaTestWebService.UPDATED_ROWS;
            break;

        case TYPE_DELETED:
            wsMethodName = AquaTestWebService.DELETED_ROWS;
            break;

        // TODO a default case should be added with error handling
        } // switch

        // this loop allows for paging of the data from the web service -
        // server returns max 1000 records at a time
        // TODO return fewer records at a time to save memory on the device?
        // e.g sample return string is almost 800,000 characters long
        while (((count + offset) < totalCount) && run) {
            // fetch data from web service
            // Log.v("DatabaseUpdater", "invoking web service [" +
            // wsMethodName + "] on table [" + table + "]");

            // java compiler optimises this "if" statement away based on
            // value of MOCK_WEB_SERVICES i.e. similar to C compiler #ifdef
            // blocks
            JSONObject jsonResponse;
            if (DebugConstants.MOCK_WEB_SERVICES) {
                // mock web services
                jsonResponse = MockAquaTestWebService.retrieveDataChanges(wsMethodName, table, lastUpdateTime,
                        (offset + count));
            } else {
                // use real production server
                jsonResponse = AquaTestWebService.retrieveDataChanges(wsMethodName, table, lastUpdateTime,
                        (offset + count));
            }

            // // Log.v("JSON_REQUEST", wsMethodName + " : " + table);

            // cancel update if so result was returned
            if (jsonResponse == null)
                return false;

            // interpret the JSON results
            //try {
            status = jsonResponse.getString(STATUS_KEY);
            //} catch (JSONException e) {

            //}

            if (status.compareTo(STATUS_SUCCESS) == 0) {
                // these fields allow for paging of the responses
                count = jsonResponse.getInt(COUNT_KEY);
                totalCount = jsonResponse.getInt(TOTAL_COUNT_KEY);
                offset = jsonResponse.getInt(OFFSET_KEY);

                // process the returned data
                if (count > 0 && jsonResponse.has(DATA_KEY)) {
                    // get the data array
                    dataArray = jsonResponse.getJSONArray(DATA_KEY);

                    // create the prepared sql statement
                    // FIXME this currently assumes that the first object
                    // contains all the field names needed
                    JSONArray dataFieldNames = dataArray.getJSONObject(0).names();
                    SQLiteStatement preparedStatement = generateQueryString(type, table, dataFieldNames);

                    try {
                        // do this to optimise the Android code
                        int dataLength = dataArray.length();

                        // loop over the returned data array
                        for (int i = 0; i < dataLength; i++) {
                            // check if thread has been cancelled
                            if (Thread.interrupted())
                                return false;

                            // get the current data record
                            JSONObject row = dataArray.getJSONObject(i);

                            // add parameters to the prepared statement
                            bindQueryParameters(preparedStatement, type, dataFieldNames, row);

                            // Log.v("SQL", "executing statement for data: "
                            // + row);

                            // execute the prepared statement
                            preparedStatement.execute();
                        } // for
                    } finally {
                        // release resources
                        preparedStatement.close();
                    }
                }
                // else exit
                else {
                    // Log.v("JSON", "empty or no data key: " + table + ", "
                    // + wsMethodName + "(" + offset + "," + count + ")");
                    run = false;
                } // else
            }
            // else the call failed, so do not continue
            else {
                // Log.v("DatabaseUpdater",
                // "web service call failed with status [" + status + "]");
                run = false;
            } // else

        } // while

        return true;
    } finally {
        // Log.v("END", "fetchAndExecuteQueries(" + type + ", " + table +
        // ")");
    }
}