@Override
    public void onCreate(SQLiteDatabase db) {
      db.beginTransaction();
      try {
        SQLiteStatement stmt;
        db.execSQL("create table capitals (prefecture text primary key, capital text not null);");
        stmt = db.compileStatement("insert into capitals values (?, ?);");

        for (String[] capital : CAPITALS) {
          stmt.bindString(1, capital[0]);
          stmt.bindString(2, capital[1]);
          stmt.executeInsert();
        }

        db.execSQL(
            "create table local_dishes (prefecture text not null, local_dish text not null);");
        stmt = db.compileStatement("insert into local_dishes values (?, ?);");

        for (String[] localDish : LOCAL_DISHES) {
          stmt.bindString(1, localDish[0]);
          stmt.bindString(2, localDish[1]);
          stmt.executeInsert();
        }
        db.setTransactionSuccessful();
      } finally {
        db.endTransaction();
      }
    }
 private boolean insertWithTags(JobHolder jobHolder) {
   final SQLiteStatement stmt = sqlHelper.getInsertStatement();
   final SQLiteStatement tagsStmt = sqlHelper.getInsertTagsStatement();
   db.beginTransaction();
   try {
     stmt.clearBindings();
     bindValues(stmt, jobHolder);
     boolean insertResult = stmt.executeInsert() != -1;
     if (!insertResult) {
       return false;
     }
     for (String tag : jobHolder.getTags()) {
       tagsStmt.clearBindings();
       bindTag(tagsStmt, jobHolder.getId(), tag);
       tagsStmt.executeInsert();
     }
     db.setTransactionSuccessful();
     return true;
   } catch (Throwable t) {
     JqLog.e(t, "error while inserting job with tags");
     return false;
   } finally {
     db.endTransaction();
   }
 }
  /**
   * 批量增加产品组合主表记录数据
   *
   * @param list
   */
  public boolean batchAddProductGroupHead(List<ProductGroupHeadData> list) {
    boolean flag = false;
    String headSql =
        "insert into ProductGroupHead(PG1_ID,PG1_M02_ID,PG1_CU1_ID,PG1_CODE,PG1_Name,PG1_CreateUser,PG1_CreateTime,PG1_ModifyUser,PG1_ModifyTime,PG1_RowVersion)"
            + "values(?,?,?,?,?,?,?,?,?,?)";
    String detailSql =
        "insert into ProductGroupDetail(PG2_ID,PG2_M02_ID,PG2_PG1_ID,PG2_PD1_ID,PG2_GroupQty,PG2_CreateUser,PG2_CreateTime,PG2_ModifyUser,PG2_ModifyTime,PG2_RowVersion)"
            + "values(?,?,?,?,?,?,?,?,?,?)";
    SQLiteDatabase db = AssetsDatabaseManager.getManager().getDatabase();
    try {
      // 开启事务
      db.beginTransaction();
      for (ProductGroupHeadData productGroupHead : list) {
        SQLiteStatement stat = db.compileStatement(headSql);
        stat.bindString(1, productGroupHead.getPg1Id());
        stat.bindString(2, productGroupHead.getPg1M02Id());
        stat.bindString(3, productGroupHead.getPg1Cu1Id());
        stat.bindString(4, productGroupHead.getPg1Code());
        stat.bindString(5, productGroupHead.getPg1Name());
        stat.bindString(6, productGroupHead.getPg1CreateUser());
        stat.bindString(7, productGroupHead.getPg1CreateTime());
        stat.bindString(8, productGroupHead.getPg1ModifyUser());
        stat.bindString(9, productGroupHead.getPg1ModifyTime());
        stat.bindString(10, productGroupHead.getPg1RowVersion());
        stat.executeInsert();

        List<ProductGroupDetailData> children = productGroupHead.getChildren();
        if (children != null) {
          for (ProductGroupDetailData productGroupDetail : children) {
            SQLiteStatement detail_stat = db.compileStatement(detailSql);
            detail_stat.bindString(1, productGroupDetail.getPg2Id());
            detail_stat.bindString(2, productGroupDetail.getPg2M02Id());
            detail_stat.bindString(3, productGroupDetail.getPg2Pg1Id());
            detail_stat.bindString(4, productGroupDetail.getPg2Pd1Id());
            detail_stat.bindLong(5, productGroupDetail.getPg2GroupQty());
            detail_stat.bindString(6, productGroupDetail.getPg2CreateUser());
            detail_stat.bindString(7, productGroupDetail.getPg2CreateTime());
            detail_stat.bindString(8, productGroupDetail.getPg2ModifyUser());
            detail_stat.bindString(9, productGroupDetail.getPg2ModifyTime());
            detail_stat.bindString(10, productGroupDetail.getPg2RowVersion());
            detail_stat.executeInsert();
          }
        }
      }
      // 数据插入成功,设置事物成功标志
      db.setTransactionSuccessful();
      // 保存数据
      db.endTransaction();
      flag = true;
    } catch (SQLException e) {
      // 结束事物,在这里没有设置成功标志,结束后不保存
      ZillionLog.e(this.getClass().getName(), e.getMessage(), e);
      db.endTransaction();
      e.printStackTrace();
    }
    return flag;
  }
  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();
    }
  }
 private long getTagId(Tag tag) {
   if (myGetTagIdStatement == null) {
     myGetTagIdStatement =
         myDatabase.compileStatement("SELECT tag_id FROM Tags WHERE parent_id = ? AND name = ?");
     myCreateTagIdStatement =
         myDatabase.compileStatement("INSERT OR IGNORE INTO Tags (parent_id,name) VALUES (?,?)");
   }
   {
     final Long id = myIdByTag.get(tag);
     if (id != null) {
       return id;
     }
   }
   if (tag.Parent != null) {
     myGetTagIdStatement.bindLong(1, getTagId(tag.Parent));
   } else {
     myGetTagIdStatement.bindNull(1);
   }
   myGetTagIdStatement.bindString(2, tag.Name);
   long id;
   try {
     id = myGetTagIdStatement.simpleQueryForLong();
   } catch (SQLException e) {
     if (tag.Parent != null) {
       myCreateTagIdStatement.bindLong(1, getTagId(tag.Parent));
     } else {
       myCreateTagIdStatement.bindNull(1);
     }
     myCreateTagIdStatement.bindString(2, tag.Name);
     id = myCreateTagIdStatement.executeInsert();
   }
   myIdByTag.put(tag, id);
   myTagById.put(id, tag);
   return id;
 }
  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 updateTables18() {
   myDatabase.execSQL("ALTER TABLE BookSeries RENAME TO BookSeries_Obsolete");
   myDatabase.execSQL(
       "CREATE TABLE BookSeries("
           + "series_id INTEGER NOT NULL REFERENCES Series(series_id),"
           + "book_id INTEGER NOT NULL UNIQUE REFERENCES Books(book_id),"
           + "book_index TEXT)");
   final SQLiteStatement insert =
       myDatabase.compileStatement(
           "INSERT INTO BookSeries (series_id,book_id,book_index) VALUES (?,?,?)");
   final Cursor cursor =
       myDatabase.rawQuery("SELECT series_id,book_id,book_index FROM BookSeries_Obsolete", null);
   while (cursor.moveToNext()) {
     insert.bindLong(1, cursor.getLong(0));
     insert.bindLong(2, cursor.getLong(1));
     final float index = cursor.getFloat(2);
     final String stringIndex;
     if (index == 0.0f) {
       stringIndex = null;
     } else {
       if (Math.abs(index - Math.round(index)) < 0.01) {
         stringIndex = String.valueOf(Math.round(index));
       } else {
         stringIndex = String.format("%.1f", index);
       }
     }
     final BigDecimal bdIndex = SeriesInfo.createIndex(stringIndex);
     SQLiteUtil.bindString(insert, 3, bdIndex != null ? bdIndex.toString() : null);
     insert.executeInsert();
   }
   cursor.close();
   myDatabase.execSQL("DROP TABLE BookSeries_Obsolete");
 }
 public long save(int id_sesion, int id_moderador) {
   // TODO Auto-generated method stub
   insertStatement.clearBindings();
   insertStatement.bindString(1, String.valueOf(id_sesion));
   insertStatement.bindString(2, String.valueOf(id_moderador));
   return insertStatement.executeInsert();
 }
  private void createVarnaStations(SQLiteDatabase db, String tableName, InputStream openRawResource)
      throws JsonParseException, JsonMappingException, IOException {
    final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    final BusStopVarnaTraffic[] all =
        OBJECT_MAPPER.readValue(openRawResource, BusStopVarnaTraffic[].class);
    final String FORMAT_SQL_INSERT =
        "INSERT INTO %s (%s, %s, %s, %s, %s) VALUES (?, ?, ?, ?, '%s')";

    final SQLiteStatement insertStatement =
        db.compileStatement(
            String.format(
                FORMAT_SQL_INSERT,
                tableName,
                Station.CODE,
                Station.LAT,
                Station.LON,
                Station.LABEL,
                Station.PROVIDER,
                FavoritiesService.PROVIDER_VARNATRAFFIC));

    for (BusStopVarnaTraffic busStopVarnaTraffic : all) {
      insertStatement.bindLong(1, busStopVarnaTraffic.getId());
      insertStatement.bindDouble(2, busStopVarnaTraffic.getPosition().getLat());
      insertStatement.bindDouble(3, busStopVarnaTraffic.getPosition().getLon());
      insertStatement.bindString(4, busStopVarnaTraffic.getText());
      insertStatement.executeInsert();
    }
  }
 public int insert(
     String statement, Object[] args, FieldType[] argFieldTypes, GeneratedKeyHolder keyHolder)
     throws SQLException {
   SQLiteStatement stmt = null;
   try {
     stmt = db.compileStatement(statement);
     bindArgs(stmt, args, argFieldTypes);
     long rowId = stmt.executeInsert();
     if (keyHolder != null) {
       keyHolder.addKey(rowId);
     }
     /*
      * I've decided to not do the CHANGES() statement here like we do down below in UPDATE because we know that
      * it worked (since it didn't throw) so we know that 1 is right.
      */
     int result = 1;
     logger.trace(
         "{}: insert statement is compiled and executed, changed {}: {}", this, result, statement);
     return result;
   } catch (android.database.SQLException e) {
     throw SqlExceptionUtil.create("inserting to database failed: " + statement, e);
   } finally {
     closeQuietly(stmt);
   }
 }
 private void addStation(Integer code, Double lat, Double lon, String label) {
   insertStatement.bindLong(1, code);
   insertStatement.bindDouble(2, lat);
   insertStatement.bindDouble(3, lon);
   insertStatement.bindString(4, label);
   insertStatement.executeInsert();
 }
 public void insertFiles(File[] files) {
   SQLiteDatabase database = dbHelper.getWritableDatabase();
   SQLiteStatement statement =
       database.compileStatement(
           "INSERT INTO "
               + TABLE_NAME
               + " ("
               + COL_FILENAME
               + ", "
               + COL_FILESIZE
               + ", "
               + COL_TIMESTAMP
               + ") VALUES (?, ?, ?)");
   database.beginTransaction();
   try {
     for (File file : files) {
       statement.bindString(1, file.getName());
       statement.bindLong(2, file.length());
       statement.bindLong(3, file.lastModified());
       statement.executeInsert();
     }
     database.setTransactionSuccessful();
   } finally {
     database.endTransaction();
   }
 }
 private void insertNormalizedNameLookup(
     SQLiteStatement stmt, long rawContactId, long dataId, int lookupType, String normalizedName) {
   stmt.bindLong(1, rawContactId);
   stmt.bindLong(2, dataId);
   stmt.bindLong(3, lookupType);
   stmt.bindString(4, normalizedName);
   stmt.executeInsert();
 }
 @Override
 protected long insertBookInfo(ZLFile file, String encoding, String language, String title) {
   if (myInsertBookInfoStatement == null) {
     myInsertBookInfoStatement =
         myDatabase.compileStatement(
             "INSERT OR IGNORE INTO Books (encoding,language,title,file_id) VALUES (?,?,?,?)");
   }
   SQLiteUtil.bindString(myInsertBookInfoStatement, 1, encoding);
   SQLiteUtil.bindString(myInsertBookInfoStatement, 2, language);
   myInsertBookInfoStatement.bindString(3, title);
   final FileInfoSet infoSet = new FileInfoSet(file);
   myInsertBookInfoStatement.bindLong(4, infoSet.getId(file));
   return myInsertBookInfoStatement.executeInsert();
 }
 /** {@inheritDoc} */
 @Override
 public boolean insert(@NonNull JobHolder jobHolder) {
   persistJobToDisk(jobHolder);
   if (jobHolder.hasTags()) {
     return insertWithTags(jobHolder);
   }
   final SQLiteStatement stmt = sqlHelper.getInsertStatement();
   stmt.clearBindings();
   bindValues(stmt, jobHolder);
   long insertId = stmt.executeInsert();
   // insert id is a alias to row_id
   jobHolder.setInsertionOrder(insertId);
   return insertId != -1;
 }
 /** {@inheritDoc} */
 @Override
 public boolean insertOrReplace(@NonNull JobHolder jobHolder) {
   if (jobHolder.getInsertionOrder() == null) {
     return insert(jobHolder);
   }
   persistJobToDisk(jobHolder);
   jobHolder.setRunningSessionId(JobManager.NOT_RUNNING_SESSION_ID);
   SQLiteStatement stmt = sqlHelper.getInsertOrReplaceStatement();
   stmt.clearBindings();
   bindValues(stmt, jobHolder);
   boolean result = stmt.executeInsert() != -1;
   JqLog.d("reinsert job result %s", result);
   return result;
 }
  private long insert(SQLiteStatement insertStatement) {
    long rowId = insertStatement.executeInsert();
    if (rowId == 0) {
      throw new RuntimeException("Insert failed");
    }

    mBatchCounter++;
    if (mBatchCounter >= INSERT_BATCH_SIZE) {
      mTargetDb.setTransactionSuccessful();
      mTargetDb.endTransaction();
      mTargetDb.beginTransaction();
      mBatchCounter = 0;
    }
    return rowId;
  }
 public long save(InstalledRecord entity) {
   insertStatement.clearBindings();
   // nov21
   // Log.i("installedread","save installed");
   insertStatement.bindString(1, entity.getPkgName());
   insertStatement.bindString(2, entity.getAppName());
   insertStatement.bindString(3, entity.getDate());
   insertStatement.bindLong(4, entity.getMiliSeconds());
   insertStatement.bindString(5, String.valueOf(entity.getLogitude()));
   insertStatement.bindString(6, String.valueOf(entity.getLatitude()));
   // insertStatement.bindDouble(5, entity.getLogitude());
   // insertStatement.bindDouble(6, entity.getLatitude());
   insertStatement.bindLong(7, entity.getNumber());
   return insertStatement.executeInsert();
 }
  private boolean insertCity(
      long id, @NonNull String name, @NonNull String country, double latitude, double longitude) {
    insertStatement.bindLong(1, id);
    insertStatement.bindString(2, name);
    insertStatement.bindString(3, country);
    insertStatement.bindDouble(4, latitude);
    insertStatement.bindDouble(5, longitude);

    long rowId = insertStatement.executeInsert();
    if (rowId < 0) {
      Log.w(LOG_TAG, "Failed to insert city: id=" + id + " name=" + name);
      return false;
    }
    return true;
  }
 /**
  * 插入一条记录,返回该记录的rowId Author: hyl Time: 2015-8-17上午11:55:55
  *
  * @param sql
  * @param args
  * @return 插入失败返回-1,成功返回rowId
  */
 public long insert(String sql, Object[] args) {
   long rowId = -1;
   SQLiteStatement statement = this.mSQLiteDataBase.compileStatement(sql);
   try {
     if (args != null) {
       for (int i = 0; i < args.length; i++) {
         bindArgs(statement, i + 1, args[i]);
       }
     }
     rowId = statement.executeInsert();
     DBLog.debug(sql, args);
   } finally {
     statement.close();
   }
   return rowId;
 }
Exemple #21
0
  // CUD local
  public Boolean salvar(Banco b, byte[] fotoPersonal) {
    /*String SQL = "INSERT INTO Personal (telefonePersonal,nomePersonal,dataDeNascimentoPersonal," +
    "emailPersonal,sexoPersonal,senhaPersonal,usuarioPersonal,fotoPersonal) " +
    "VALUES('" + super.getTelefone() + "','"+ super.getNome() + "','" + super.getDataDeNascimento() +
    "','" + super.getEmail() + "','" + super.getSexo() + "','"  +
    super.getSenha() + "','" 	+ super.getUsuario() + "', '" + super.getFoto() + "')";
    */

    String SQL =
        "INSERT INTO Personal ("
            + "telefonePersonal,"
            + "nomePersonal,"
            + "dataDeNascimentoPersonal,"
            + "emailPersonal,"
            + "sexoPersonal,"
            + "senhaPersonal,"
            + "usuarioPersonal,"
            + "fotoPersonal,"
            + "ativo) values "
            + "(?, ?, ?, ? , ?, ? ,? ,? ,?)";

    SQLiteStatement statement = b.getWritableDatabase().compileStatement(SQL);
    statement.bindString(1, super.getTelefone());
    statement.bindString(2, super.getNome());
    statement.bindString(3, super.getDataDeNascimento());
    statement.bindString(4, super.getEmail());
    statement.bindString(5, super.getSexo());
    statement.bindString(6, super.getSenha());
    statement.bindString(7, super.getUsuario());
    statement.bindBlob(8, fotoPersonal);
    statement.bindString(9, "ativado");

    /*String SQL = "INSERT INTO Personal (telefonePersonal,nomePersonal,dataDeNascimentoPersonal," +
                      "emailPersonal,sexoPersonal,senhaPersonal,usuarioPersonal,fotoPersonal,ativo) " +
                      "VALUES('" + super.getTelefone()+ "','"+ super.getNome() + "','" + super.getDataDeNascimento() +
                      "','" + super.getEmail() + "','" + super.getSexo() + "','"  +
                      super.getSenha() + "','" 	+ super.getUsuario() + "','"+ foto + "','ativado');";
    //  System.out.println(SQL);*/
    try {
      statement.executeInsert();
      return true;
    } catch (Exception ex) {
      // System.out.println(ex.toString());
      ex.printStackTrace();
      return false;
    }
  }
 public long insertHistory(
     String meid_dec, String meid_hex, String esn_dec, String esn_hex, String metropcs_spc) {
   SQLiteStatement statement =
       this.db.compileStatement(
           "INSERT INTO history (created_at,meid_dec,meid_hex,esn_dec,esn_hex,metropcs_spc) VALUES(date('now'),'"
               + meid_dec
               + "','"
               + meid_hex
               + "','"
               + esn_dec
               + "','"
               + esn_hex
               + "','"
               + metropcs_spc
               + "');");
   return statement.executeInsert();
 }
Exemple #23
0
  /**
   * Adds the given API call to the queue.
   *
   * @param apiCall The call to add to the queue.
   */
  public boolean addToQueue(AbstractAnalyticsApiCall apiCall) {
    SQLiteDatabase db = getWritableDatabase();
    if (insert == null) {
      insert =
          db.compileStatement(
              "INSERT INTO " + TABLE_QUEUE + " (write_key, endpoint, payload) VALUES (?, ?, ?)");
    }

    // Params are 1 indexed, not 0
    insert.bindString(1, apiCall.getWriteKey());
    insert.bindString(2, apiCall.getApiEndpoint());
    insert.bindString(3, apiCall.getPayload());

    boolean success = insert.executeInsert() == 1;

    return success;
  }
  private void insertValues(SQLiteDatabase db, String query) {
    Cursor c = null;
    try {
      c = db.rawQuery(query, null);
      if (c == null) return;
      if (c.isBeforeFirst() && !c.moveToFirst()) return;

      while (true) {
        insert.bindLong(1, c.getInt(0)); // id
        insert.bindString(2, c.getString(1)); // title
        insert.bindLong(3, c.getInt(2)); // unread
        insert.executeInsert();
        if (!c.moveToNext()) break;
      }
    } finally {
      if (c != null && !c.isClosed()) c.close();
    }
  }
 /**
  * 增加产品组合主表记录 单条
  *
  * @param productGroupHead
  * @return
  */
 public boolean addProductGroupHead(ProductGroupHeadData productGroupHead) {
   String insertSql =
       "insert into ProductGroupHead(PG1_ID,PG1_M02_ID,PG1_CU1_ID,PG1_CODE,PG1_Name,PG1_CreateUser,PG1_CreateTime,PG1_ModifyUser,PG1_ModifyTime,PG1_RowVersion)"
           + "values(?,?,?,?,?,?,?,?,?,?)";
   SQLiteDatabase db = AssetsDatabaseManager.getManager().getDatabase();
   SQLiteStatement stat = db.compileStatement(insertSql);
   stat.bindString(1, productGroupHead.getPg1Id());
   stat.bindString(2, productGroupHead.getPg1M02Id());
   stat.bindString(3, productGroupHead.getPg1Cu1Id());
   stat.bindString(4, productGroupHead.getPg1Code());
   stat.bindString(5, productGroupHead.getPg1Name());
   stat.bindString(6, productGroupHead.getPg1CreateUser());
   stat.bindString(7, productGroupHead.getPg1CreateTime());
   stat.bindString(8, productGroupHead.getPg1ModifyUser());
   stat.bindString(9, productGroupHead.getPg1ModifyTime());
   stat.bindString(10, productGroupHead.getPg1RowVersion());
   long i = stat.executeInsert();
   return i > 0;
 }
  public void setEstoque(VO_Materiais materiais) {
    try {
      String queryString = Contrato_VendasFacil.Materiais.UPDATE_ESTOQUE;

      // todo: getWritableDatabase
      DAO_VendasFacil dao = new DAO_VendasFacil(fragmento);
      SQLiteDatabase db = dao.getTabelaGravacao();

      SQLiteStatement query = db.compileStatement(queryString);

      query.bindDouble(1, materiais.getQtdEstoque());
      query.bindLong(2, materiais.getDataUltimaCompraAsLong());
      query.bindLong(3, materiais.getCodMaterialInteger());

      query.executeInsert();
      db.close();
      // todo: close()
    } catch (Exception e) {
      Toasts.mensagemErro(fragmento, e.getMessage(), "DAO_Material.setEstoque");
    }
  }
  @Override
  protected long saveBookmark(Bookmark bookmark) {
    SQLiteStatement statement;
    if (bookmark.getId() == -1) {
      if (myInsertBookmarkStatement == null) {
        myInsertBookmarkStatement =
            myDatabase.compileStatement(
                "INSERT OR IGNORE INTO Bookmarks (book_id,bookmark_text,creation_time,modification_time,access_time,access_counter,model_id,paragraph,word,char,visible) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
      }
      statement = myInsertBookmarkStatement;
    } else {
      if (myUpdateBookmarkStatement == null) {
        myUpdateBookmarkStatement =
            myDatabase.compileStatement(
                "UPDATE Bookmarks SET book_id = ?, bookmark_text = ?, creation_time =?, modification_time = ?,access_time = ?, access_counter = ?, model_id = ?, paragraph = ?, word = ?, char = ?, visible = ? WHERE bookmark_id = ?");
      }
      statement = myUpdateBookmarkStatement;
    }

    statement.bindLong(1, bookmark.getBookId());
    statement.bindString(2, bookmark.getText());
    SQLiteUtil.bindDate(statement, 3, bookmark.getTime(Bookmark.CREATION));
    SQLiteUtil.bindDate(statement, 4, bookmark.getTime(Bookmark.MODIFICATION));
    SQLiteUtil.bindDate(statement, 5, bookmark.getTime(Bookmark.ACCESS));
    statement.bindLong(6, bookmark.getAccessCount());
    SQLiteUtil.bindString(statement, 7, bookmark.ModelId);
    statement.bindLong(8, bookmark.ParagraphIndex);
    statement.bindLong(9, bookmark.ElementIndex);
    statement.bindLong(10, bookmark.CharIndex);
    statement.bindLong(11, bookmark.IsVisible ? 1 : 0);

    if (statement == myInsertBookmarkStatement) {
      return statement.executeInsert();
    } else {
      final long id = bookmark.getId();
      statement.bindLong(12, id);
      statement.execute();
      return id;
    }
  }
  public void setMateriais(VO_Materiais materiais, int operacao) {
    try {
      String queryString = null;

      switch (operacao) {
        case INSERE:
          queryString = Contrato_VendasFacil.Materiais.INSERT;
          break;

        case ATUALIZA:
          queryString = Contrato_VendasFacil.Materiais.UPDATE;
          break;
      }

      if (materiais.getCodMaterialString().isEmpty()) {
        materiais.setCodMaterial(proximoCodigoMaterial());
      }
      // todo: getWritableDatabase
      DAO_VendasFacil dao = new DAO_VendasFacil(fragmento);
      SQLiteDatabase db = dao.getTabelaGravacao();

      SQLiteStatement query = db.compileStatement(queryString);

      // Ambas as querys (insert e update) estão montadas com os campos na mesma sequencia
      // Assim é possível utilizar o mesmo trecho de código abaixo para ambos os casos.
      query.bindString(1, materiais.getDesMaterial());
      query.bindBlob(2, materiais.getFotoByteArray());
      query.bindDouble(3, materiais.getQtdMinima());
      query.bindDouble(4, materiais.getQtdEstoque());
      query.bindLong(5, materiais.getCodUnidadeMedida());
      query.bindLong(6, materiais.getDataUltimaCompraAsLong());
      query.bindLong(7, materiais.getCodMaterialInteger());

      query.executeInsert();
      db.close();
      // todo: close()
    } catch (Exception e) {
      Toasts.mensagemErro(fragmento, e.getMessage(), "DAO_Material.setMateriais");
    }
  }
 /**
  * Perform an internal string-to-integer lookup using the compiled {@link SQLiteStatement}
  * provided. If a mapping isn't found in database, it will be created. All new, uncached answers
  * are added to the cache automatically.
  *
  * @param query Compiled statement used to query for the mapping.
  * @param insert Compiled statement used to insert a new mapping when no existing one is found in
  *     cache or from query.
  * @param value Value to find mapping for.
  * @param cache In-memory cache of previous answers.
  * @return An unique integer mapping for the given value.
  */
 private long lookupAndCacheId(
     SQLiteStatement query, SQLiteStatement insert, String value, HashMap<String, Long> cache) {
   long id = -1;
   try {
     // Try searching database for mapping
     DatabaseUtils.bindObjectToProgram(query, 1, value);
     id = query.simpleQueryForLong();
   } catch (SQLiteDoneException e) {
     // Nothing found, so try inserting new mapping
     DatabaseUtils.bindObjectToProgram(insert, 1, value);
     id = insert.executeInsert();
   }
   if (id != -1) {
     // Cache and return the new answer
     cache.put(value, id);
     return id;
   } else {
     // Otherwise throw if no mapping found or created
     throw new IllegalStateException(
         "Couldn't find or create internal " + "lookup table entry for value " + value);
   }
 }
 protected void saveFileInfo(FileInfo fileInfo) {
   final long id = fileInfo.Id;
   SQLiteStatement statement;
   if (id == -1) {
     if (myInsertFileInfoStatement == null) {
       myInsertFileInfoStatement =
           myDatabase.compileStatement(
               "INSERT OR IGNORE INTO Files (name,parent_id,size) VALUES (?,?,?)");
     }
     statement = myInsertFileInfoStatement;
   } else {
     if (myUpdateFileInfoStatement == null) {
       myUpdateFileInfoStatement =
           myDatabase.compileStatement(
               "UPDATE Files SET name = ?, parent_id = ?, size = ? WHERE file_id = ?");
     }
     statement = myUpdateFileInfoStatement;
   }
   statement.bindString(1, fileInfo.Name);
   final FileInfo parent = fileInfo.Parent;
   if (parent != null) {
     statement.bindLong(2, parent.Id);
   } else {
     statement.bindNull(2);
   }
   final long size = fileInfo.FileSize;
   if (size != -1) {
     statement.bindLong(3, size);
   } else {
     statement.bindNull(3);
   }
   if (id == -1) {
     fileInfo.Id = statement.executeInsert();
   } else {
     statement.bindLong(4, id);
     statement.execute();
   }
 }