@MediumTest
  public void testStatementConstraint() throws Exception {
    mDatabase.execSQL("CREATE TABLE test (num INTEGER NOT NULL);");
    SQLiteStatement statement = mDatabase.compileStatement("INSERT INTO test (num) VALUES (?)");

    // Try to insert NULL, which violates the constraint
    try {
      statement.clearBindings();
      statement.execute();
      fail("expected exception not thrown");
    } catch (SQLiteConstraintException e) {
      // expected
    }

    // Make sure the statement can still be used
    statement.bindLong(1, 1);
    statement.execute();
    statement.close();

    Cursor c = mDatabase.query("test", null, null, null, null, null, null);
    int numCol = c.getColumnIndexOrThrow("num");
    c.moveToFirst();
    long num = c.getLong(numCol);
    assertEquals(1, num);
    c.close();
  }
예제 #2
0
  /** update the level and count for the given flashcard in the database. */
  private void updateFlashcard(Flashcard fc) {
    openDB();

    _curDB.beginTransaction();
    try {
      // Delete old entry if any.
      SQLiteStatement dStmt = getCompiledStatement(SQL_DELETE_FCS);
      dStmt.bindString(1, fc.getLang1Str());
      dStmt.execute();

      // insert new state entry.
      SQLiteStatement iStmt = getCompiledStatement(SQL_INSERT_FCS);
      iStmt.bindString(1, fc.getLang1Str());
      iStmt.bindLong(2, fc.getLevel());
      iStmt.bindLong(3, fc.getRightGuessCount());
      iStmt.execute();
      _curDB.setTransactionSuccessful();
    } catch (SQLException e) {
      MsgDispatcher.sendMessageToUI(
          MsgType.MSG_SHOW_ERROR_MSG, 0, 0, "unable to update id=" + fc.getID());
    } finally {
      _curDB.endTransaction();
    }

    // this flashcard is no longer used by anyone so release it.
    fc.release();
  }
  protected void saveBookSeriesInfo(long bookId, SeriesInfo seriesInfo) {
    if (myGetSeriesIdStatement == null) {
      myGetSeriesIdStatement =
          myDatabase.compileStatement("SELECT series_id FROM Series WHERE name = ?");
      myInsertSeriesStatement =
          myDatabase.compileStatement("INSERT OR IGNORE INTO Series (name) VALUES (?)");
      myInsertBookSeriesStatement =
          myDatabase.compileStatement(
              "INSERT OR REPLACE INTO BookSeries (book_id,series_id,book_index) VALUES (?,?,?)");
      myDeleteBookSeriesStatement =
          myDatabase.compileStatement("DELETE FROM BookSeries WHERE book_id = ?");
    }

    if (seriesInfo == null) {
      myDeleteBookSeriesStatement.bindLong(1, bookId);
      myDeleteBookSeriesStatement.execute();
    } else {
      long seriesId;
      try {
        myGetSeriesIdStatement.bindString(1, seriesInfo.Name);
        seriesId = myGetSeriesIdStatement.simpleQueryForLong();
      } catch (SQLException e) {
        myInsertSeriesStatement.bindString(1, seriesInfo.Name);
        seriesId = myInsertSeriesStatement.executeInsert();
      }
      myInsertBookSeriesStatement.bindLong(1, bookId);
      myInsertBookSeriesStatement.bindLong(2, seriesId);
      SQLiteUtil.bindString(
          myInsertBookSeriesStatement,
          3,
          seriesInfo.Index != null ? seriesInfo.Index.toString() : null);
      myInsertBookSeriesStatement.execute();
    }
  }
    @Override
    public void onCreate(SQLiteDatabase database) {
      database.execSQL(
          "create table if not exists urlpermission("
              + " id integer primary key autoincrement,"
              + " service_name text,"
              + " url text,"
              + " rule text);");

      SQLiteStatement statement =
          database.compileStatement(
              "insert into urlpermission(service_name, url, rule) values(?,?,?)");
      int index = 1;
      statement.bindString(index++, "service1");
      statement.bindString(index++, "http://www.baidu.com/1");
      statement.bindString(index++, "YES");

      statement.execute();

      index = 1;
      statement.bindString(index++, "service2");
      statement.bindString(index++, "http://www.baidu.com/2");
      statement.bindString(index++, "NO");
      statement.execute();

      statement.close();
    }
예제 #5
0
 List<String> trimCache(long amount) {
   ArrayList<String> pathList = new ArrayList<String>(100);
   Cursor cursor = null;
   final String query = "SELECT contentlength, filepath FROM cache ORDER BY expires ASC";
   try {
     cursor = mCacheDatabase.rawQuery(query, null);
     if (cursor.moveToFirst()) {
       int batchSize = 100;
       StringBuilder pathStr = new StringBuilder(20 + 16 * batchSize);
       pathStr.append("DELETE FROM cache WHERE filepath IN (?");
       for (int i = 1; i < batchSize; i++) {
         pathStr.append(", ?");
       }
       pathStr.append(")");
       SQLiteStatement statement = null;
       try {
         statement = mCacheDatabase.compileStatement(pathStr.toString());
         // as bindString() uses 1-based index, initialize index to 1
         int index = 1;
         do {
           long length = cursor.getLong(0);
           if (length == 0) {
             continue;
           }
           amount -= length;
           String filePath = cursor.getString(1);
           statement.bindString(index, filePath);
           pathList.add(filePath);
           if (index++ == batchSize) {
             statement.execute();
             statement.clearBindings();
             index = 1;
           }
         } while (cursor.moveToNext() && amount > 0);
         if (index > 1) {
           // there may be old bindings from the previous statement
           // if index is less than batchSize, which is Ok.
           statement.execute();
         }
       } catch (IllegalStateException e) {
         Log.e(LOGTAG, "trimCache SQLiteStatement", e);
       } finally {
         if (statement != null) statement.close();
       }
     }
   } catch (IllegalStateException e) {
     Log.e(LOGTAG, "trimCache Cursor", e);
   } finally {
     if (cursor != null) cursor.close();
   }
   return pathList;
 }
예제 #6
0
 private void deleteOldLessons(long groupId) {
   try {
     mDb.beginTransaction();
     mDeleteStatement.bindLong(1, groupId);
     mDeleteStatement.execute();
     mDeleteInformationStatement.bindLong(1, groupId);
     mDeleteInformationStatement.execute();
     mDb.setTransactionSuccessful();
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     mDb.endTransaction();
   }
 }
  protected void saveBookAuthorInfo(long bookId, long index, Author author) {
    if (myGetAuthorIdStatement == null) {
      myGetAuthorIdStatement =
          myDatabase.compileStatement(
              "SELECT author_id FROM Authors WHERE name = ? AND sort_key = ?");
      myInsertAuthorStatement =
          myDatabase.compileStatement("INSERT OR IGNORE INTO Authors (name,sort_key) VALUES (?,?)");
      myInsertBookAuthorStatement =
          myDatabase.compileStatement(
              "INSERT OR REPLACE INTO BookAuthor (book_id,author_id,author_index) VALUES (?,?,?)");
    }

    long authorId;
    try {
      myGetAuthorIdStatement.bindString(1, author.DisplayName);
      myGetAuthorIdStatement.bindString(2, author.SortKey);
      authorId = myGetAuthorIdStatement.simpleQueryForLong();
    } catch (SQLException e) {
      myInsertAuthorStatement.bindString(1, author.DisplayName);
      myInsertAuthorStatement.bindString(2, author.SortKey);
      authorId = myInsertAuthorStatement.executeInsert();
    }
    myInsertBookAuthorStatement.bindLong(1, bookId);
    myInsertBookAuthorStatement.bindLong(2, authorId);
    myInsertBookAuthorStatement.bindLong(3, index);
    myInsertBookAuthorStatement.execute();
  }
  private void insertPhone(
      Cursor c,
      SQLiteStatement phoneInsert,
      SQLiteStatement phoneLookupInsert,
      SQLiteStatement hasPhoneUpdate) {
    long lastUpdatedContact = -1;
    long id = c.getLong(PhonesQuery.PERSON);
    String number = c.getString(PhonesQuery.NUMBER);
    String normalizedNumber = null;
    if (number != null) {
      normalizedNumber = PhoneNumberUtils.getStrippedReversed(number);
    }
    phoneInsert.bindLong(PhoneInsert.RAW_CONTACT_ID, id);
    phoneInsert.bindLong(PhoneInsert.MIMETYPE_ID, mPhoneMimetypeId);
    bindString(phoneInsert, PhoneInsert.IS_PRIMARY, c.getString(PhonesQuery.ISPRIMARY));
    bindString(phoneInsert, PhoneInsert.NUMBER, number);
    bindString(phoneInsert, PhoneInsert.TYPE, c.getString(PhonesQuery.TYPE));
    bindString(phoneInsert, PhoneInsert.LABEL, c.getString(PhonesQuery.LABEL));
    bindString(phoneInsert, PhoneInsert.NORMALIZED_NUMBER, normalizedNumber);

    long dataId = insert(phoneInsert);
    if (normalizedNumber != null) {
      phoneLookupInsert.bindLong(PhoneLookupInsert.RAW_CONTACT_ID, id);
      phoneLookupInsert.bindLong(PhoneLookupInsert.DATA_ID, dataId);
      phoneLookupInsert.bindString(PhoneLookupInsert.NORMALIZED_NUMBER, normalizedNumber);
      insert(phoneLookupInsert);

      if (lastUpdatedContact != id) {
        lastUpdatedContact = id;
        hasPhoneUpdate.bindLong(HasPhoneNumberUpdate.CONTACT_ID, id);
        hasPhoneUpdate.execute();
      }
    }
  }
예제 #9
0
파일: TileCache.java 프로젝트: hanchao/vtm
  public void saveTile(Tile tile, ByteArrayOutputStream data, boolean success) {
    byte[] bytes = null;

    if (success) bytes = data.toByteArray();

    synchronized (mCacheBuffers) {
      data.reset();
      mCacheBuffers.add(data);
    }

    if (dbg) log.debug("store tile {} {}", tile, Boolean.valueOf(success));

    if (!success) return;

    synchronized (mStmtPutTile) {
      mStmtPutTile.bindLong(1, tile.tileX);
      mStmtPutTile.bindLong(2, tile.tileY);
      mStmtPutTile.bindLong(3, tile.zoomLevel);
      mStmtPutTile.bindLong(4, 0);
      mStmtPutTile.bindLong(5, 0);
      mStmtPutTile.bindBlob(6, bytes);

      mStmtPutTile.execute();
      mStmtPutTile.clearBindings();
    }
  }
  // @Large
  @Suppress
  public void testLoadingThreadDelayRegisterData() throws Exception {
    mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, data INT);");

    final int count = 505;
    String sql = "INSERT INTO test (data) VALUES (?);";
    SQLiteStatement s = mDatabase.compileStatement(sql);
    for (int i = 0; i < count; i++) {
      s.bindLong(1, i);
      s.execute();
    }

    int maxRead = 500;
    int initialRead = 5;
    SQLiteCursor c =
        (SQLiteCursor) mDatabase.rawQuery("select * from test;", null, initialRead, maxRead);

    TestObserver observer = new TestObserver(count, c);
    c.getCount();
    c.registerDataSetObserver(observer);
    if (!observer.quit) {
      Looper.loop();
    }
    c.close();
  }
  @MediumTest
  public void testStatementMultipleBindings() throws Exception {
    mDatabase.execSQL("CREATE TABLE test (num INTEGER, str TEXT);");
    SQLiteStatement statement =
        mDatabase.compileStatement("INSERT INTO test (num, str) VALUES (?, ?)");

    for (long i = 0; i < 10; i++) {
      statement.bindLong(1, i);
      statement.bindString(2, Long.toHexString(i));
      statement.execute();
    }
    statement.close();

    Cursor c = mDatabase.query("test", null, null, null, null, null, "ROWID");
    int numCol = c.getColumnIndexOrThrow("num");
    int strCol = c.getColumnIndexOrThrow("str");
    assertTrue(c.moveToFirst());
    for (long i = 0; i < 10; i++) {
      long num = c.getLong(numCol);
      String str = c.getString(strCol);
      assertEquals(i, num);
      assertEquals(Long.toHexString(i), str);
      c.moveToNext();
    }
    c.close();
  }
  /**
   * Called by the ManageLocations screen to update a location in the database
   *
   * @param id
   * @param locationName
   * @param coordinates
   * @param description
   * @return
   */
  public boolean updateLocationData(
      int id, String locationName, String coordinates, String description) {
    boolean success = false;

    SQLiteDatabase db = getReadableDatabase();

    String sql =
        "UPDATE locations SET locationName = ?, coordinates = ?, description = ? where _id = ?";

    SQLiteStatement sqlStatement = db.compileStatement(sql);
    sqlStatement.bindString(1, locationName);
    sqlStatement.bindString(2, coordinates);
    sqlStatement.bindString(3, description);
    sqlStatement.bindLong(4, id);

    db.beginTransaction();
    try {
      sqlStatement.execute();
      db.setTransactionSuccessful();
      success = true;
    } catch (SQLException ex) {
      ex.printStackTrace();
    } finally {
      db.endTransaction();
      sqlStatement.close();
      db.close();
    }

    return success;
  }
  @Override
  public void changeStoredSamplesType(
      int timestampFrom, int timestampTo, byte kind, SampleProvider provider) {
    try (SQLiteDatabase db = this.getReadableDatabase()) {
      String sql =
          "UPDATE "
              + TABLE_GBACTIVITYSAMPLES
              + " SET "
              + KEY_TYPE
              + "= ? WHERE "
              + KEY_PROVIDER
              + " = ? AND "
              + KEY_TIMESTAMP
              + " >= ? AND "
              + KEY_TIMESTAMP
              + " < ? ;"; // do not use BETWEEN because the range is inclusive in that case!

      SQLiteStatement statement = db.compileStatement(sql);
      statement.bindLong(1, kind);
      statement.bindLong(2, provider.getID());
      statement.bindLong(3, timestampFrom);
      statement.bindLong(4, timestampTo);
      statement.execute();
    }
  }
예제 #14
0
  /** Insert a set of flashcards (linked list) in a single transaction. */
  private void insertFlashcardSet(Flashcard head) {
    openDB();
    SQLiteStatement stmt = getCompiledStatement(SQL_INSERT_FC);
    boolean gotError = false;

    _curDB.beginTransaction();
    try {
      for (Flashcard fc = head; fc != null; fc = Flashcard.Chain.getNext(fc)) {

        stmt.bindLong(1, _importState.getRandomId());
        stmt.bindString(2, fc.getLang1Str());
        stmt.bindString(3, fc.getLang2Str());
        stmt.execute();
      }
      _curDB.setTransactionSuccessful();
    } catch (SQLException e) {
      gotError = true;
      MsgDispatcher.sendMessageToUI(MsgType.MSG_SHOW_ERROR_MSG, 0, 0, "unable to insert fc");
    } finally {
      _curDB.endTransaction();
    }

    Flashcard.Chain.releaseChain(head);

    // tell controller to send us more data if insert went fine.
    if (!gotError) {
      MsgDispatcher.sendMessageToController(MsgType.MSG_CONTINUE_IMPORT, 0, 0, null);
    }
  }
예제 #15
0
 /**
  * Adds or updates room.
  *
  * @param account
  * @param room
  * @param nickname
  * @param password
  * @param join
  */
 void write(String account, String room, String nickname, String password, boolean join) {
   synchronized (writeLock) {
     if (writeStatement == null) {
       SQLiteDatabase db = databaseManager.getWritableDatabase();
       writeStatement =
           db.compileStatement(
               "INSERT OR REPLACE INTO "
                   + NAME
                   + " ("
                   + Fields.ACCOUNT
                   + ", "
                   + Fields.ROOM
                   + ", "
                   + Fields.NICKNAME
                   + ", "
                   + Fields.PASSWORD
                   + ", "
                   + Fields.NEED_JOIN
                   + ") VALUES (?, ?, ?, ?, ?);");
     }
     writeStatement.bindString(1, account);
     writeStatement.bindString(2, room);
     writeStatement.bindString(3, nickname);
     writeStatement.bindString(4, password);
     writeStatement.bindLong(5, join ? 1 : 0);
     writeStatement.execute();
   }
 }
예제 #16
0
  public void updateHomeWork(HomeWork hw) {
    try {
      mDb.beginTransaction();
      if (hw != null) {

        mUpdateHomeWorkStatement.clearBindings();
        if (hw.isComplite()) {
          mUpdateHomeWorkStatement.bindLong(1, 1);
          NotificationManager.getInstance().removeNotification(hw);

        } else {
          mUpdateHomeWorkStatement.bindLong(1, 0);
          NotificationManager.getInstance().addNewNotification(hw);
        }

        if (hw.getMessage() != null) {
          mUpdateHomeWorkStatement.bindString(2, hw.getMessage());
        }

        if (hw.getMessage() != null) {
          mUpdateHomeWorkStatement.bindBlob(3, Slipper.serializeObject(hw.getImages()));
        }

        mUpdateHomeWorkStatement.bindLong(4, hw.getId());
        mUpdateHomeWorkStatement.execute();
      }
      mDb.setTransactionSuccessful();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      mDb.endTransaction();
    }
  }
  @Override
  public void addGBActivitySamples(ActivitySample[] activitySamples) {
    try (SQLiteDatabase db = this.getWritableDatabase()) {

      String sql =
          "INSERT INTO "
              + TABLE_GBACTIVITYSAMPLES
              + " ("
              + KEY_TIMESTAMP
              + ","
              + KEY_PROVIDER
              + ","
              + KEY_INTENSITY
              + ","
              + KEY_STEPS
              + ","
              + KEY_TYPE
              + ")"
              + " VALUES (?,?,?,?,?);";
      SQLiteStatement statement = db.compileStatement(sql);
      db.beginTransaction();

      for (ActivitySample activitySample : activitySamples) {
        statement.clearBindings();
        statement.bindLong(1, activitySample.getTimestamp());
        statement.bindLong(2, activitySample.getProvider().getID());
        statement.bindLong(3, activitySample.getRawIntensity());
        statement.bindLong(4, activitySample.getSteps());
        statement.bindLong(5, activitySample.getRawKind());
        statement.execute();
      }
      db.setTransactionSuccessful();
      db.endTransaction();
    }
  }
  private static void migrateConversation(
      Context context,
      MasterSecret masterSecret,
      Handler handler,
      long theirThreadId,
      long ourThreadId) {
    SmsDatabase ourSmsDatabase = DatabaseFactory.getSmsDatabase(context);
    Cursor cursor = null;

    try {
      Uri uri = Uri.parse("content://sms/conversations/" + theirThreadId);
      cursor = context.getContentResolver().query(uri, null, null, null, null);
      SQLiteDatabase transaction = ourSmsDatabase.beginTransaction();
      SQLiteStatement statement = ourSmsDatabase.createInsertStatement(transaction);

      while (cursor != null && cursor.moveToNext()) {
        getContentValuesForRow(context, masterSecret, cursor, ourThreadId, statement);
        statement.execute();

        Message msg =
            handler.obtainMessage(SECONDARY_PROGRESS_UPDATE, 10000 / cursor.getCount(), 0);
        handler.sendMessage(msg);
      }

      ourSmsDatabase.endTransaction(transaction);
      DatabaseFactory.getThreadDatabase(context).update(ourThreadId);
      DatabaseFactory.getThreadDatabase(context).notifyConversationListeners(ourThreadId);

    } finally {
      if (cursor != null) cursor.close();
    }
  }
예제 #19
0
 public void addTerms(ArrayList<Terms> termList, User usr) {
   System.out.println("Terms StartUp : " + System.currentTimeMillis());
   if (!isTermsAvailableForCompany(usr.getCompanyId())) {
     deleteTerms();
     SQLiteDatabase db = this.getWritableDatabase();
     try {
       db.beginTransaction();
       SQLiteStatement statement = db.compileStatement(this.TERMS_QUERY);
       for (Terms terms : termList) {
         statement.bindString(1, terms.description);
         statement.bindLong(2, terms.languageId);
         statement.bindString(3, terms.term);
         statement.bindString(4, usr.getCompanyId());
         statement.execute();
         statement.clearBindings();
       }
       db.setTransactionSuccessful();
     } catch (Exception e) {
       // TODO: handle exception
     } finally {
       db.endTransaction();
       db.close();
     }
   }
   System.out.println("Terms End : " + System.currentTimeMillis());
 }
  /**
   * Called by ManageLocations screen to add a location to the database
   *
   * @param locationName
   * @param coordinates
   * @param description
   * @return
   */
  public boolean addLocationData(String locationName, String coordinates, String description) {
    boolean success = false;

    SQLiteDatabase db = getReadableDatabase();

    SQLiteStatement sqlStatement =
        db.compileStatement(
            "INSERT INTO locations (locationName, coordinates, description) VALUES (?, ?, ?)");
    sqlStatement.bindString(1, locationName);
    sqlStatement.bindString(2, coordinates);
    sqlStatement.bindString(3, description);

    db.beginTransaction();
    try {
      sqlStatement.execute();
      db.setTransactionSuccessful();
      success = true;
    } catch (SQLException ex) {
      ex.printStackTrace();
    } finally {
      db.endTransaction();
      sqlStatement.close();
      db.close();
    }

    return success;
  }
 public void upsertContentWifiNode(
     ContentValues values, String selection, String[] selectionArgs) {
   long rowID = getContentId(values.getAsString(SizzoSchema.CONTENTS.Columns.UID));
   if (rowID > 0) {
     if (mStatementUpdateWifiNode == null) {
       mStatementUpdateWifiNode =
           getWritableDatabase()
               .compileStatement(
                   "UPDATE "
                       + SizzoSchema.CONTENTS.TABLE
                       + " SET "
                       + SizzoSchema.CONTENTS.Columns.TITLE
                       + "=?, "
                       + SizzoSchema.CONTENTS.Columns.DETAIL
                       + "=?, "
                       + SizzoSchema.CONTENTS.Columns.TYPE
                       + "=?, "
                       + SizzoSchema.CONTENTS.Columns.LASTUPDATEDDATE
                       + "=date('now')"
                       + " WHERE "
                       + SizzoSchema.CONTENTS.Columns.UID
                       + "=?");
     }
     bindString(
         mStatementUpdateWifiNode, 1, values.getAsString(SizzoSchema.CONTENTS.Columns.TITLE));
     bindString(
         mStatementUpdateWifiNode, 2, values.getAsString(SizzoSchema.CONTENTS.Columns.DETAIL));
     bindString(mStatementUpdateWifiNode, 3, SizzoSchema.CONTENTS.Types.WIFI.name());
     bindString(mStatementUpdateWifiNode, 4, values.getAsString(SizzoSchema.CONTENTS.Columns.UID));
     mStatementUpdateWifiNode.execute();
   }
 }
 private int update(String statement, Object[] args, FieldType[] argFieldTypes, String label)
     throws SQLException {
   SQLiteStatement stmt = null;
   try {
     stmt = db.compileStatement(statement);
     bindArgs(stmt, args, argFieldTypes);
     stmt.execute();
   } catch (android.database.SQLException e) {
     throw SqlExceptionUtil.create("updating database failed: " + statement, e);
   } finally {
     closeQuietly(stmt);
     stmt = null;
   }
   int result;
   try {
     stmt = db.compileStatement("SELECT CHANGES()");
     result = (int) stmt.simpleQueryForLong();
   } catch (android.database.SQLException e) {
     // ignore the exception and just return 1
     result = 1;
   } finally {
     closeQuietly(stmt);
   }
   logger.trace("{} statement is compiled and executed, changed {}: {}", label, result, statement);
   return result;
 }
  private void updateTables6() {
    myDatabase.execSQL("ALTER TABLE Bookmarks ADD COLUMN model_id TEXT");

    myDatabase.execSQL("ALTER TABLE Books ADD COLUMN file_id INTEGER");

    myDatabase.execSQL("DELETE FROM Files");
    final FileInfoSet infoSet = new FileInfoSet();
    Cursor cursor = myDatabase.rawQuery("SELECT file_name FROM Books", null);
    while (cursor.moveToNext()) {
      infoSet.check(ZLFile.createFileByPath(cursor.getString(0)).getPhysicalFile(), false);
    }
    cursor.close();
    infoSet.save();

    cursor = myDatabase.rawQuery("SELECT book_id,file_name FROM Books", null);
    final SQLiteStatement deleteStatement =
        myDatabase.compileStatement("DELETE FROM Books WHERE book_id = ?");
    final SQLiteStatement updateStatement =
        myDatabase.compileStatement("UPDATE Books SET file_id = ? WHERE book_id = ?");
    while (cursor.moveToNext()) {
      final long bookId = cursor.getLong(0);
      final long fileId = infoSet.getId(ZLFile.createFileByPath(cursor.getString(1)));

      if (fileId == -1) {
        deleteStatement.bindLong(1, bookId);
        deleteStatement.execute();
      } else {
        updateStatement.bindLong(1, fileId);
        updateStatement.bindLong(2, bookId);
        updateStatement.execute();
      }
    }
    cursor.close();

    myDatabase.execSQL("ALTER TABLE Books RENAME TO Books_Obsolete");
    myDatabase.execSQL(
        "CREATE TABLE Books("
            + "book_id INTEGER PRIMARY KEY,"
            + "encoding TEXT,"
            + "language TEXT,"
            + "title TEXT NOT NULL,"
            + "file_id INTEGER UNIQUE NOT NULL REFERENCES Files(file_id))");
    myDatabase.execSQL(
        "INSERT INTO Books (book_id,encoding,language,title,file_id) SELECT book_id,encoding,language,title,file_id FROM Books_Obsolete");
    myDatabase.execSQL("DROP TABLE Books_Obsolete");
  }
 protected void deleteAllBookTags(long bookId) {
   if (myDeleteBookTagsStatement == null) {
     myDeleteBookTagsStatement =
         myDatabase.compileStatement("DELETE FROM BookTag WHERE book_id = ?");
   }
   myDeleteBookTagsStatement.bindLong(1, bookId);
   myDeleteBookTagsStatement.execute();
 }
 private void delete(String id) {
   pendingCancelations.remove(id);
   db.beginTransaction();
   try {
     SQLiteStatement stmt = sqlHelper.getDeleteStatement();
     stmt.clearBindings();
     stmt.bindString(1, id);
     stmt.execute();
     SQLiteStatement deleteTagsStmt = sqlHelper.getDeleteJobTagsStatement();
     deleteTagsStmt.bindString(1, id);
     deleteTagsStmt.execute();
     db.setTransactionSuccessful();
     jobStorage.delete(id);
   } finally {
     db.endTransaction();
   }
 }
예제 #26
0
 public void executeSQL(String sql) {
   Context context = getContext();
   final SQLiteDatabase db = getDatabaseByDefaultPath(context);
   SQLiteStatement statement = db.compileStatement(sql);
   if (statement != null) {
     statement.execute();
   }
 }
 protected void removeFromFavorites(long bookId) {
   if (myRemoveFromFavoritesStatement == null) {
     myRemoveFromFavoritesStatement =
         myDatabase.compileStatement("DELETE FROM Favorites WHERE book_id = ?");
   }
   myRemoveFromFavoritesStatement.bindLong(1, bookId);
   myRemoveFromFavoritesStatement.execute();
 }
 protected void addToFavorites(long bookId) {
   if (myAddToFavoritesStatement == null) {
     myAddToFavoritesStatement =
         myDatabase.compileStatement("INSERT OR IGNORE INTO Favorites(book_id) VALUES (?)");
   }
   myAddToFavoritesStatement.bindLong(1, bookId);
   myAddToFavoritesStatement.execute();
 }
  private void deleteVisitedHyperlinks(long bookId) {
    if (myDeleteVisitedHyperlinksStatement == null) {
      myDeleteVisitedHyperlinksStatement =
          myDatabase.compileStatement("DELETE FROM VisitedHyperlinks WHERE book_id = ?");
    }

    myDeleteVisitedHyperlinksStatement.bindLong(1, bookId);
    myDeleteVisitedHyperlinksStatement.execute();
  }
 protected boolean insertIntoBookList(long bookId) {
   if (myInsertIntoBookListStatement == null) {
     myInsertIntoBookListStatement =
         myDatabase.compileStatement("INSERT OR IGNORE INTO BookList(book_id) VALUES (?)");
   }
   myInsertIntoBookListStatement.bindLong(1, bookId);
   myInsertIntoBookListStatement.execute();
   return true;
 }