/** @inheritdoc */ @Override protected void bindValues(SQLiteStatement stmt, Location entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } Integer location_id = entity.getLocation_id(); if (location_id != null) { stmt.bindLong(2, location_id); } String name = entity.getName(); if (name != null) { stmt.bindString(3, name); } String venue_name = entity.getVenue_name(); if (venue_name != null) { stmt.bindString(4, venue_name); } String address = entity.getAddress(); if (address != null) { stmt.bindString(5, address); } String district = entity.getDistrict(); if (district != null) { stmt.bindString(6, district); } String region = entity.getRegion(); if (region != null) { stmt.bindString(7, region); } String province = entity.getProvince(); if (province != null) { stmt.bindString(8, province); } Double latitude = entity.getLatitude(); if (latitude != null) { stmt.bindDouble(9, latitude); } Double longitude = entity.getLongitude(); if (longitude != null) { stmt.bindDouble(10, longitude); } stmt.bindLong(11, entity.getEvent_id()); }
/** @inheritdoc */ @Override protected void bindValues(SQLiteStatement stmt, Incidente entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } String idServidor = entity.getIdServidor(); if (idServidor != null) { stmt.bindString(2, idServidor); } stmt.bindString(3, entity.getTitulo()); String descripcion = entity.getDescripcion(); if (descripcion != null) { stmt.bindString(4, descripcion); } Integer zona = entity.getZona(); if (zona != null) { stmt.bindLong(5, zona); } Integer gravedad = entity.getGravedad(); if (gravedad != null) { stmt.bindLong(6, gravedad); } Double latitud = entity.getLatitud(); if (latitud != null) { stmt.bindDouble(7, latitud); } Double longitud = entity.getLongitud(); if (longitud != null) { stmt.bindDouble(8, longitud); } java.util.Date fechaCreacion = entity.getFechaCreacion(); if (fechaCreacion != null) { stmt.bindLong(9, fechaCreacion.getTime()); } String usuarioCreacion = entity.getUsuarioCreacion(); if (usuarioCreacion != null) { stmt.bindString(10, usuarioCreacion); } }
/** @inheritdoc */ @Override protected void bindValues(SQLiteStatement stmt, kinetics entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } Float anglex = entity.getAnglex(); if (anglex != null) { stmt.bindDouble(2, anglex); } Float angley = entity.getAngley(); if (angley != null) { stmt.bindDouble(3, angley); } Float agnlez = entity.getAgnlez(); if (agnlez != null) { stmt.bindDouble(4, agnlez); } Float accelx = entity.getAccelx(); if (accelx != null) { stmt.bindDouble(5, accelx); } Float accely = entity.getAccely(); if (accely != null) { stmt.bindDouble(6, accely); } Float accelz = entity.getAccelz(); if (accelz != null) { stmt.bindDouble(7, accelz); } Float gyrox = entity.getGyrox(); if (gyrox != null) { stmt.bindDouble(8, gyrox); } Float gyroy = entity.getGyroy(); if (gyroy != null) { stmt.bindDouble(9, gyroy); } Float gyroz = entity.getGyroz(); if (gyroz != null) { stmt.bindDouble(10, gyroz); } }
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; }
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(); }
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(); } }
/** * 绑定参数 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("未知参数类型,请检查绑定参数"); } }
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"); } }
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); } } } }
public static void addAmbient(SQLiteDatabase db, AmbientDB a) { try { db.beginTransaction(); SQLiteStatement stmt = db.compileStatement(AmbientDB.INSERT_SQL); stmt.clearBindings(); stmt.bindString(1, a.ambientId); stmt.bindDouble(2, a.temperature); stmt.bindLong(3, a.light); stmt.execute(); stmt.close(); db.setTransactionSuccessful(); } finally { if (db.inTransaction()) { db.endTransaction(); } } }
public static void updateAmbient(SQLiteDatabase db, ArrayList<AmbientDB> aList) { try { db.beginTransaction(); SQLiteStatement stmt = db.compileStatement(AmbientDB.UPDATE_SQL); for (int n = 0; n < aList.size(); n++) { AmbientDB u = aList.get(n); stmt.clearBindings(); stmt.bindString(3, u.ambientId); stmt.bindDouble(1, u.temperature); stmt.bindLong(2, u.light); stmt.execute(); } stmt.close(); db.setTransactionSuccessful(); } finally { if (db.inTransaction()) { db.endTransaction(); } } }
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"); } }
public SQLiteStatement getStatement(SQLiteStatement statement, long objectId, int courseID) throws Exception { if (courseID != 0 && getUserMailAddress() != null && !getUserMailAddress().equals("") && getCreatedAt() != null && getLastModified() != null) { statement.clearBindings(); statement.bindLong(1, objectId); statement.bindString(2, getUserMailAddress()); statement.bindLong(3, courseID); statement.bindDouble(4, getRating()); statement.bindLong(5, createdAt.getTime()); statement.bindLong(6, lastModified.getTime()); if (comment == null) comment = ""; statement.bindString(7, getComment()); return statement; } else { return null; } }
/** @inheritdoc */ @Override protected void bindValues(SQLiteStatement stmt, Order entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } String type = entity.getType(); if (type != null) { stmt.bindString(2, type); } String topic = entity.getTopic(); if (topic != null) { stmt.bindString(3, topic); } String startTime = entity.getStartTime(); if (startTime != null) { stmt.bindString(4, startTime); } String endTime = entity.getEndTime(); if (endTime != null) { stmt.bindString(5, endTime); } Double price = entity.getPrice(); if (price != null) { stmt.bindDouble(6, price); } Boolean realtime = entity.getRealtime(); if (realtime != null) { stmt.bindLong(7, realtime ? 1L : 0L); } String contactName = entity.getContactName(); if (contactName != null) { stmt.bindString(8, contactName); } String contactGender = entity.getContactGender(); if (contactGender != null) { stmt.bindString(9, contactGender); } String contactPhone = entity.getContactPhone(); if (contactPhone != null) { stmt.bindString(10, contactPhone); } Long expertId = entity.getExpertId(); if (expertId != null) { stmt.bindLong(11, expertId); } Long userId = entity.getUserId(); if (userId != null) { stmt.bindLong(12, userId); } }
/** 数据绑定 * */ 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]); } } }
protected void bindValues(SQLiteStatement sqlitestatement, FoodLogEntry foodlogentry) { sqlitestatement.clearBindings(); Object obj = foodlogentry.getId(); if (obj != null) { sqlitestatement.bindLong(1, ((Long) (obj)).longValue()); } obj = foodlogentry.getServerId(); if (obj != null) { sqlitestatement.bindLong(2, ((Long) (obj)).longValue()); } obj = foodlogentry.getUuid(); if (obj != null) { sqlitestatement.bindString(3, ((String) (obj))); } obj = foodlogentry.getTimeCreated(); if (obj != null) { sqlitestatement.bindLong(4, ((Date) (obj)).getTime()); } obj = foodlogentry.getTimeUpdated(); if (obj != null) { sqlitestatement.bindLong(5, ((Date) (obj)).getTime()); } obj = foodlogentry.getEntityStatus(); if (obj != null) { sqlitestatement.bindLong(6, ((Integer) (obj)).intValue()); } obj = foodlogentry.getValue(); if (obj != null) { sqlitestatement.bindDouble(7, ((Double) (obj)).doubleValue()); } obj = foodlogentry.getTrackerType(); if (obj != null) { sqlitestatement.bindString(8, ((String) (obj))); } obj = foodlogentry.getLogDate(); if (obj != null) { sqlitestatement.bindLong(9, ((Date) (obj)).getTime()); } obj = foodlogentry.getIsQuickCaloriesAdd(); if (obj != null) { long l; if (((Boolean) (obj)).booleanValue()) { l = 1L; } else { l = 0L; } sqlitestatement.bindLong(10, l); } obj = foodlogentry.getAmount(); if (obj != null) { sqlitestatement.bindDouble(11, ((Double) (obj)).doubleValue()); } obj = foodlogentry.getBrand(); if (obj != null) { sqlitestatement.bindString(12, ((String) (obj))); } obj = foodlogentry.getCalories(); if (obj != null) { sqlitestatement.bindDouble(13, ((Double) (obj)).doubleValue()); } obj = foodlogentry.getMealType(); if (obj != null) { sqlitestatement.bindLong(14, ((Integer) (obj)).intValue()); } obj = foodlogentry.getName(); if (obj != null) { sqlitestatement.bindString(15, ((String) (obj))); } obj = foodlogentry.getUnitName(); if (obj != null) { sqlitestatement.bindString(16, ((String) (obj))); } obj = foodlogentry.getUnitNamePlural(); if (obj != null) { sqlitestatement.bindString(17, ((String) (obj))); } foodlogentry = foodlogentry.getFoodId(); if (foodlogentry != null) { sqlitestatement.bindLong(18, foodlogentry.longValue()); } }
public void executeSqlBatch( String[] queryarr, JSONArray[] jsonparams, String[] queryIDs, String tx_id) { try { this.myDb.beginTransaction(); String query = ""; String query_id = ""; int len = queryarr.length; for (int i = 0; i < len; i++) { query = queryarr[i]; query_id = queryIDs[i]; if (query.toLowerCase().startsWith("insert") && jsonparams != null) { SQLiteStatement myStatement = this.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 { myStatement.bindString(j + 1, jsonparams[i].getString(j)); } } long insertId = myStatement.executeInsert(); String result = "{'insertId':'" + insertId + "'}"; this.sendJavascript( "SQLitePluginTransaction.queryCompleteCallback('" + tx_id + "','" + query_id + "', " + result + ");"); } else { String[] params = null; if (jsonparams != null) { params = new String[jsonparams[i].length()]; for (int j = 0; j < jsonparams[i].length(); j++) { params[j] = jsonparams[i].getString(j); if (params[j] == "null") // XXX better check params[j] = ""; } } Cursor myCursor = this.myDb.rawQuery(query, params); this.processResults(myCursor, query_id, tx_id); myCursor.close(); } } this.myDb.setTransactionSuccessful(); } catch (SQLiteException ex) { ex.printStackTrace(); Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage()); this.sendJavascript( "SQLitePluginTransaction.txErrorCallback('" + tx_id + "', '" + ex.getMessage() + "');"); } catch (JSONException ex) { ex.printStackTrace(); Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage()); this.sendJavascript( "SQLitePluginTransaction.txErrorCallback('" + tx_id + "', '" + ex.getMessage() + "');"); } finally { this.myDb.endTransaction(); Log.v("executeSqlBatch", tx_id); this.sendJavascript("SQLitePluginTransaction.txCompleteCallback('" + tx_id + "');"); } }
/** @inheritdoc */ @Override protected void bindValues(SQLiteStatement stmt, FavoItem entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } ReaderItemType type = entity.getType(); if (type != null) { stmt.bindString(2, typeConverter.convertToDatabaseValue(type)); } String actualId = entity.getActualId(); if (actualId != null) { stmt.bindString(3, actualId); } Timestamp addDate = entity.getAddDate(); if (addDate != null) { stmt.bindLong(4, addDateConverter.convertToDatabaseValue(addDate)); } String url = entity.getUrl(); if (url != null) { stmt.bindString(5, url); } String title = entity.getTitle(); if (title != null) { stmt.bindString(6, title); } String excerpt = entity.getExcerpt(); if (excerpt != null) { stmt.bindString(7, excerpt); } String thumbC = entity.getThumbC(); if (thumbC != null) { stmt.bindString(8, thumbC); } Long otherId = entity.getOtherId(); if (otherId != null) { stmt.bindLong(9, otherId); } String author = entity.getAuthor(); if (author != null) { stmt.bindString(10, author); } String authorEmail = entity.getAuthorEmail(); if (authorEmail != null) { stmt.bindString(11, authorEmail); } String authorUrl = entity.getAuthorUrl(); if (authorUrl != null) { stmt.bindString(12, authorUrl); } Timestamp date = entity.getDate(); if (date != null) { stmt.bindLong(13, dateConverter.convertToDatabaseValue(date)); } Long votePositive = entity.getVotePositive(); if (votePositive != null) { stmt.bindLong(14, votePositive); } Long voteNegative = entity.getVoteNegative(); if (voteNegative != null) { stmt.bindLong(15, voteNegative); } Long commentCount = entity.getCommentCount(); if (commentCount != null) { stmt.bindLong(16, commentCount); } String threadId = entity.getThreadId(); if (threadId != null) { stmt.bindString(17, threadId); } String content = entity.getContent(); if (content != null) { stmt.bindString(18, content); } String textContent = entity.getTextContent(); if (textContent != null) { stmt.bindString(19, textContent); } String pics = entity.getPics(); if (pics != null) { stmt.bindString(20, pics); } String picFirst = entity.getPicFirst(); if (picFirst != null) { stmt.bindString(21, picFirst); } Long picCount = entity.getPicCount(); if (picCount != null) { stmt.bindLong(22, picCount); } Boolean hasGif = entity.getHasGif(); if (hasGif != null) { stmt.bindLong(23, hasGif ? 1L : 0L); } String videoThumbnail = entity.getVideoThumbnail(); if (videoThumbnail != null) { stmt.bindString(24, videoThumbnail); } String videoTitle = entity.getVideoTitle(); if (videoTitle != null) { stmt.bindString(25, videoTitle); } String videoDescription = entity.getVideoDescription(); if (videoDescription != null) { stmt.bindString(26, videoDescription); } Float videoDuration = entity.getVideoDuration(); if (videoDuration != null) { stmt.bindDouble(27, videoDuration); } String videoLink = entity.getVideoLink(); if (videoLink != null) { stmt.bindString(28, videoLink); } String videoPlayer = entity.getVideoPlayer(); if (videoPlayer != null) { stmt.bindString(29, videoPlayer); } String videoSource = entity.getVideoSource(); if (videoSource != null) { stmt.bindString(30, videoSource); } }
/** @inheritdoc */ @Override protected void bindValues(SQLiteStatement stmt, CapitalMarketsRevenue entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } String clientId = entity.getClientId(); if (clientId != null) { stmt.bindString(2, clientId); } String clientName = entity.getClientName(); if (clientName != null) { stmt.bindString(3, clientName); } String clientTier = entity.getClientTier(); if (clientTier != null) { stmt.bindString(4, clientTier); } Float grossComm = entity.getGrossComm(); if (grossComm != null) { stmt.bindDouble(5, grossComm); } String month = entity.getMonth(); if (month != null) { stmt.bindString(6, month); } String productId = entity.getProductId(); if (productId != null) { stmt.bindString(7, productId); } String productName = entity.getProductName(); if (productName != null) { stmt.bindString(8, productName); } Float profitLoss = entity.getProfitLoss(); if (profitLoss != null) { stmt.bindDouble(9, profitLoss); } String region = entity.getRegion(); if (region != null) { stmt.bindString(10, region); } Integer year = entity.getYear(); if (year != null) { stmt.bindLong(11, year); } String scope = entity.getScope(); if (scope != null) { stmt.bindString(12, scope); } String objectId = entity.getObjectId(); if (objectId != null) { stmt.bindString(13, objectId); } java.util.Date _cacheUpdatedAt = entity.get_cacheUpdatedAt(); if (_cacheUpdatedAt != null) { stmt.bindLong(14, _cacheUpdatedAt.getTime()); } Long apCachedRequestId = entity.getApCachedRequestId(); if (apCachedRequestId != null) { stmt.bindLong(15, apCachedRequestId); } }
/** * 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); }