private void insertRawContact(Cursor c, SQLiteStatement insert) {
    long id = c.getLong(PeopleQuery._ID);
    insert.bindLong(RawContactsInsert.ID, id);
    insert.bindLong(RawContactsInsert.CONTACT_ID, id);
    bindString(insert, RawContactsInsert.CUSTOM_RINGTONE, c.getString(PeopleQuery.CUSTOM_RINGTONE));
    bindString(insert, RawContactsInsert.DIRTY, c.getString(PeopleQuery._SYNC_DIRTY));
    insert.bindLong(
        RawContactsInsert.LAST_TIME_CONTACTED, c.getLong(PeopleQuery.LAST_TIME_CONTACTED));
    insert.bindLong(RawContactsInsert.SEND_TO_VOICEMAIL, c.getLong(PeopleQuery.SEND_TO_VOICEMAIL));
    insert.bindLong(RawContactsInsert.STARRED, c.getLong(PeopleQuery.STARRED));
    insert.bindLong(RawContactsInsert.TIMES_CONTACTED, c.getLong(PeopleQuery.TIMES_CONTACTED));
    bindString(insert, RawContactsInsert.SYNC1, c.getString(PeopleQuery._SYNC_TIME));
    bindString(insert, RawContactsInsert.SYNC2, c.getString(PeopleQuery._SYNC_LOCAL_ID));
    bindString(insert, RawContactsInsert.DISPLAY_NAME, c.getString(PeopleQuery.NAME));

    String account = c.getString(PeopleQuery._SYNC_ACCOUNT);
    if (!TextUtils.isEmpty(account)) {
      bindString(insert, RawContactsInsert.ACCOUNT_NAME, account);
      bindString(insert, RawContactsInsert.ACCOUNT_TYPE, DEFAULT_ACCOUNT_TYPE);
      bindString(insert, RawContactsInsert.SOURCE_ID, c.getString(PeopleQuery._SYNC_ID));
    } else {
      insert.bindNull(RawContactsInsert.ACCOUNT_NAME);
      insert.bindNull(RawContactsInsert.ACCOUNT_TYPE);
      insert.bindNull(RawContactsInsert.SOURCE_ID);
    }
    insert(insert);
  }
 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;
 }
 private void bindLong(SQLiteStatement stmt, int index, Number value) {
   if (value == null) {
     stmt.bindNull(index);
   } else {
     stmt.bindLong(index, value.longValue());
   }
 }
 private void bindString(SQLiteStatement stmt, int index, String value) {
   if (value == null) {
     stmt.bindNull(index);
   } else {
     stmt.bindString(index, value);
   }
 }
示例#5
0
 private void bindStringOrNull(SQLiteStatement statement, int index, String str) {
   if (str == null) {
     statement.bindNull(index);
   } else {
     statement.bindString(index, str);
   }
 }
 private void bindString(SQLiteStatement insert, int index, String string) {
   if (string == null) {
     insert.bindNull(index);
   } else {
     insert.bindString(index, string);
   }
 }
示例#7
0
 /**
  * 绑定参数 Author: hyl Time: 2015-8-17上午10:42:43
  *
  * @param statement
  * @param position
  * @param args
  */
 private void bindArgs(SQLiteStatement statement, int position, Object args) {
   int type = FieldTypeManager.getValueType(args);
   switch (type) {
     case FieldTypeManager.VALUE_TYPE_NULL:
       statement.bindNull(position);
       break;
     case FieldTypeManager.BASE_TYPE_BYTE_ARRAY:
       statement.bindBlob(position, (byte[]) args);
       break;
     case FieldTypeManager.BASE_TYPE_CHAR:
     case FieldTypeManager.BASE_TYPE_STRING:
       statement.bindString(position, args.toString());
       break;
     case FieldTypeManager.BASE_TYPE_DATE:
       statement.bindString(position, DateUtil.formatDatetime((Date) args));
       break;
     case FieldTypeManager.BASE_TYPE_DOUBLE:
     case FieldTypeManager.BASE_TYPE_FLOAT:
       statement.bindDouble(position, Double.parseDouble(args.toString()));
       break;
     case FieldTypeManager.BASE_TYPE_INT:
     case FieldTypeManager.BASE_TYPE_LONG:
     case FieldTypeManager.BASE_TYPE_SHORT:
       statement.bindLong(position, Long.parseLong(args.toString()));
       break;
     case FieldTypeManager.NOT_BASE_TYPE:
       throw new IllegalArgumentException("未知参数类型,请检查绑定参数");
   }
 }
 private static void addEncryptedStringToStatement(
     Context context,
     SQLiteStatement statement,
     Cursor cursor,
     MasterSecret masterSecret,
     int index,
     String key) {
   int columnIndex = cursor.getColumnIndexOrThrow(key);
   if (cursor.isNull(columnIndex)) statement.bindNull(index);
   else
     statement.bindString(
         index, encryptIfNecessary(context, masterSecret, cursor.getString(columnIndex)));
 }
  private void insertGroup(Cursor c, SQLiteStatement insert) {
    long id = c.getLong(GroupsQuery.ID);

    insert.bindLong(GroupsInsert.ID, id);
    bindString(insert, GroupsInsert.TITLE, c.getString(GroupsQuery.NAME));
    bindString(insert, GroupsInsert.NOTES, c.getString(GroupsQuery.NOTES));
    bindString(insert, GroupsInsert.SYSTEM_ID, c.getString(GroupsQuery.SYSTEM_ID));
    insert.bindLong(GroupsInsert.DIRTY, c.getLong(GroupsQuery._SYNC_DIRTY));
    insert.bindLong(GroupsInsert.GROUP_VISIBLE, 1);

    String account = c.getString(GroupsQuery._SYNC_ACCOUNT);
    if (!TextUtils.isEmpty(account)) {
      bindString(insert, GroupsInsert.ACCOUNT_NAME, account);
      bindString(insert, GroupsInsert.ACCOUNT_TYPE, DEFAULT_ACCOUNT_TYPE);
      bindString(insert, GroupsInsert.SOURCE_ID, c.getString(GroupsQuery._SYNC_ID));
    } else {
      insert.bindNull(GroupsInsert.ACCOUNT_NAME);
      insert.bindNull(GroupsInsert.ACCOUNT_TYPE);
      insert.bindNull(GroupsInsert.SOURCE_ID);
    }
    insert(insert);
  }
 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();
   }
 }
 private void bindArgs(SQLiteStatement stmt, Object[] args, FieldType[] argFieldTypes)
     throws SQLException {
   if (args == null) {
     return;
   }
   for (int i = 0; i < args.length; i++) {
     Object arg = args[i];
     if (arg == null) {
       stmt.bindNull(i + 1);
     } else {
       SqlType sqlType = argFieldTypes[i].getSqlType();
       switch (sqlType) {
         case STRING:
         case LONG_STRING:
         case CHAR:
           stmt.bindString(i + 1, arg.toString());
           break;
         case BOOLEAN:
         case BYTE:
         case SHORT:
         case INTEGER:
         case LONG:
           stmt.bindLong(i + 1, ((Number) arg).longValue());
           break;
         case FLOAT:
         case DOUBLE:
           stmt.bindDouble(i + 1, ((Number) arg).doubleValue());
           break;
         case BYTE_ARRAY:
         case SERIALIZABLE:
           stmt.bindBlob(i + 1, (byte[]) arg);
           break;
         case DATE:
           // this is mapped to a STRING under Android
         case BLOB:
           // this is only for derby serializable
         case BIG_DECIMAL:
           // this should be handled as a STRING
           throw new SQLException("Invalid Android type: " + sqlType);
         case UNKNOWN:
         default:
           throw new SQLException("Unknown sql argument type: " + sqlType);
       }
     }
   }
 }
  private void insertPhoto(Cursor c, SQLiteStatement insert, SQLiteStatement photoIdUpdate) {
    if (c.isNull(PhotosQuery.DATA)) {
      return;
    }

    long personId = c.getLong(PhotosQuery.PERSON);

    insert.bindLong(PhotoInsert.RAW_CONTACT_ID, personId);
    insert.bindLong(PhotoInsert.MIMETYPE_ID, mPhotoMimetypeId);
    insert.bindBlob(PhotoInsert.PHOTO, c.getBlob(PhotosQuery.DATA));

    String account = c.getString(PhotosQuery._SYNC_ACCOUNT);
    if (!TextUtils.isEmpty(account)) {
      insert.bindString(PhotoInsert.SYNC1, c.getString(PhotosQuery._SYNC_ID));
    } else {
      insert.bindNull(PhotoInsert.SYNC1);
    }

    long rowId = insert(insert);
    photoIdUpdate.bindLong(PhotoIdUpdate.PHOTO_ID, rowId);
    photoIdUpdate.bindLong(PhotoIdUpdate.CONTACT_ID, personId);
    photoIdUpdate.execute();
  }
  /** 数据绑定 * */
  private void bindValues(SQLiteStatement stmt, T entity) {
    for (int i = 0; i < mSetArgs.length; i++) {
      int stmtIndex = i + 1;
      try {
        Field field = mClazz.getDeclaredField(mSetArgs[i]);
        field.setAccessible(true);

        Type columnType = field.getType();
        if (String.class.equals(columnType)) {
          String value = (String) field.get(entity);
          if (value == null) {
            stmt.bindNull(stmtIndex);
          } else {
            stmt.bindString(stmtIndex, value);
          }

        } else if (columnType.equals(Integer.class) || columnType.equals(int.class)) {
          int value = field.getInt(entity);
          stmt.bindLong(stmtIndex, value);

        } else if (columnType.equals(Float.class) || columnType.equals(float.class)) {
          float value = field.getFloat(entity);
          stmt.bindDouble(stmtIndex, value);

        } else if (columnType.equals(Double.class) || columnType.equals(double.class)) {
          double value = field.getDouble(entity);
          stmt.bindDouble(stmtIndex, value);

        } else if (columnType.equals(Long.class) || columnType.equals(long.class)) {
          long value = field.getLong(entity);
          stmt.bindLong(stmtIndex, value);

        } else {
          Object obj = field.get(entity);
          if (obj == null) {
            stmt.bindNull(stmtIndex);
          } else {
            byte[] value = SerializeHelper.serialize(obj);
            stmt.bindBlob(stmtIndex, value);
          }
        }

      } catch (NoSuchFieldException e) {
        e.printStackTrace();
        stmt.bindNull(stmtIndex);
        continue;
      } catch (IllegalAccessException e) {
        e.printStackTrace();
        stmt.bindNull(stmtIndex);
        continue;
      } catch (IllegalArgumentException e) {
        e.printStackTrace();
        stmt.bindNull(stmtIndex);
        continue;
      }
    }

    if (mWhereArgs != null) {
      for (int i = 0; i < mWhereArgs.length; i++) {
        int columnIndex = mSetArgs.length + i + 1;
        stmt.bindString(columnIndex, mWhereArgValues[i]);
      }
    }
  }
 private static void addIntToStatement(
     SQLiteStatement statement, Cursor cursor, int index, String key) {
   int columnIndex = cursor.getColumnIndexOrThrow(key);
   if (cursor.isNull(columnIndex)) statement.bindNull(index);
   else statement.bindLong(index, cursor.getLong(columnIndex));
 }
  /**
   * Executes a batch request and sends the results via sendJavascriptCB().
   *
   * @param dbname The name of the database.
   * @param queryarr Array of query strings
   * @param jsonparams Array of JSON query parameters
   * @param queryIDs Array of query ids
   * @param cbc Callback context from Cordova API
   */
  private void executeSqlBatch(
      String dbname,
      String[] queryarr,
      JSONArray[] jsonparams,
      String[] queryIDs,
      CallbackContext cbc) {
    SQLiteDatabase mydb = this.getDatabase(dbname);

    if (mydb == null) return;

    String query = "";
    String query_id = "";
    int len = queryarr.length;

    JSONArray batchResults = new JSONArray();

    for (int i = 0; i < len; i++) {
      query_id = queryIDs[i];

      JSONObject queryResult = null;
      String errorMessage = "unknown";

      try {
        boolean needRawQuery = true;

        query = queryarr[i];

        // UPDATE or DELETE:
        // NOTE: this code should be safe to RUN with old Android SDK.
        // To BUILD with old Android SDK remove lines from HERE: {{
        if (android.os.Build.VERSION.SDK_INT >= 11
            && (query.toLowerCase().startsWith("update")
                || query.toLowerCase().startsWith("delete"))) {
          SQLiteStatement myStatement = mydb.compileStatement(query);

          if (jsonparams != null) {
            for (int j = 0; j < jsonparams[i].length(); j++) {
              if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double) {
                myStatement.bindDouble(j + 1, jsonparams[i].getDouble(j));
              } else if (jsonparams[i].get(j) instanceof Number) {
                myStatement.bindLong(j + 1, jsonparams[i].getLong(j));
              } else if (jsonparams[i].isNull(j)) {
                myStatement.bindNull(j + 1);
              } else {
                myStatement.bindString(j + 1, jsonparams[i].getString(j));
              }
            }
          }

          int rowsAffected = -1; // (assuming invalid)

          // Use try & catch just in case android.os.Build.VERSION.SDK_INT >= 11 is lying:
          try {
            rowsAffected = myStatement.executeUpdateDelete();
            // Indicate valid results:
            needRawQuery = false;
          } catch (SQLiteException ex) {
            // Indicate problem & stop this query:
            ex.printStackTrace();
            errorMessage = ex.getMessage();
            Log.v(
                "executeSqlBatch", "SQLiteStatement.executeUpdateDelete(): Error=" + errorMessage);
            needRawQuery = false;
          } catch (Exception ex) {
            // Assuming SDK_INT was lying & method not found:
            // do nothing here & try again with raw query.
          }

          if (rowsAffected != -1) {
            queryResult = new JSONObject();
            queryResult.put("rowsAffected", rowsAffected);
          }
        } // to HERE. }}

        // INSERT:
        if (query.toLowerCase().startsWith("insert") && jsonparams != null) {
          needRawQuery = false;

          SQLiteStatement myStatement = mydb.compileStatement(query);

          for (int j = 0; j < jsonparams[i].length(); j++) {
            if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double) {
              myStatement.bindDouble(j + 1, jsonparams[i].getDouble(j));
            } else if (jsonparams[i].get(j) instanceof Number) {
              myStatement.bindLong(j + 1, jsonparams[i].getLong(j));
            } else if (jsonparams[i].isNull(j)) {
              myStatement.bindNull(j + 1);
            } else {
              myStatement.bindString(j + 1, jsonparams[i].getString(j));
            }
          }

          long insertId = -1; // (invalid)

          try {
            insertId = myStatement.executeInsert();
          } catch (SQLiteException ex) {
            ex.printStackTrace();
            errorMessage = ex.getMessage();
            Log.v("executeSqlBatch", "SQLiteDatabase.executeInsert(): Error=" + errorMessage);
          }

          if (insertId != -1) {
            queryResult = new JSONObject();
            queryResult.put("insertId", insertId);
            queryResult.put("rowsAffected", 1);
          }
        }

        if (query.toLowerCase().startsWith("begin")) {
          needRawQuery = false;
          try {
            mydb.beginTransaction();

            queryResult = new JSONObject();
            queryResult.put("rowsAffected", 0);
          } catch (SQLiteException ex) {
            ex.printStackTrace();
            errorMessage = ex.getMessage();
            Log.v("executeSqlBatch", "SQLiteDatabase.beginTransaction(): Error=" + errorMessage);
          }
        }

        if (query.toLowerCase().startsWith("commit")) {
          needRawQuery = false;
          try {
            mydb.setTransactionSuccessful();
            mydb.endTransaction();

            queryResult = new JSONObject();
            queryResult.put("rowsAffected", 0);
          } catch (SQLiteException ex) {
            ex.printStackTrace();
            errorMessage = ex.getMessage();
            Log.v(
                "executeSqlBatch",
                "SQLiteDatabase.setTransactionSuccessful/endTransaction(): Error=" + errorMessage);
          }
        }

        if (query.toLowerCase().startsWith("rollback")) {
          needRawQuery = false;
          try {
            mydb.endTransaction();

            queryResult = new JSONObject();
            queryResult.put("rowsAffected", 0);
          } catch (SQLiteException ex) {
            ex.printStackTrace();
            errorMessage = ex.getMessage();
            Log.v("executeSqlBatch", "SQLiteDatabase.endTransaction(): Error=" + errorMessage);
          }
        }

        // raw query for other statements:
        if (needRawQuery) {
          String[] params = null;

          if (jsonparams != null) {
            params = new String[jsonparams[i].length()];

            for (int j = 0; j < jsonparams[i].length(); j++) {
              if (jsonparams[i].isNull(j)) params[j] = "";
              else params[j] = jsonparams[i].getString(j);
            }
          }

          Cursor myCursor = mydb.rawQuery(query, params);

          if (query_id.length() > 0) {
            queryResult = this.getRowsResultFromQuery(myCursor);
          }

          myCursor.close();
        }
      } catch (Exception ex) {
        ex.printStackTrace();
        errorMessage = ex.getMessage();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql[Batch](): Error=" + errorMessage);
      }

      try {
        if (queryResult != null) {
          JSONObject r = new JSONObject();
          r.put("qid", query_id);

          r.put("type", "success");
          r.put("result", queryResult);

          batchResults.put(r);
        } else {
          JSONObject r = new JSONObject();
          r.put("qid", query_id);
          r.put("type", "error");

          JSONObject er = new JSONObject();
          er.put("message", errorMessage);
          r.put("result", er);

          batchResults.put(r);
        }
      } catch (JSONException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql[Batch](): Error=" + ex.getMessage());
        // TODO what to do?
      }
    }

    cbc.success(batchResults);
  }