Used by INSERT, DELETE, UPDATE operations. This class will return
a more appropriate message when there is no data source.
764984
void checkDataReadOnly() {

        if (dataSource.length() == 0) {
            throw Error.error(ErrorCode.TEXT_TABLE_UNKNOWN_DATA_SOURCE);
        }

        if (isReadOnly) {
            throw Error.error(ErrorCode.DATA_IS_READONLY);
        }
    }
824171
@Override
  protected void deleteEntity(DbEntityOperation operation) {

    final DbEntity dbEntity = operation.getEntity();

    // get statement
    String deleteStatement = dbSqlSessionFactory.getDeleteStatement(dbEntity.getClass());
    ensureNotNull("no delete statement for " + dbEntity.getClass() + " in the ibatis mapping files", "deleteStatement", deleteStatement);

    LOG.executeDatabaseOperation("DELETE", dbEntity);

    // execute the delete
    int nrOfRowsDeleted = executeDelete(deleteStatement, dbEntity);
    operation.setRowsAffected(nrOfRowsDeleted);

    // It only makes sense to check for optimistic locking exceptions for objects that actually have a revision
    if (dbEntity instanceof HasDbRevision && nrOfRowsDeleted == 0) {
      operation.setFailed(true);
      return;
    }

    // perform post delete action
    entityDeleted(dbEntity);
  }
1372900
public int update(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {
		if (mappedUpdate == null) {
			mappedUpdate = MappedUpdate.build(dao, tableInfo);
		}
		int result = mappedUpdate.update(databaseConnection, data, objectCache);
		if (dao != null && !localIsInBatchMode.get()) {
			dao.notifyChanges();
		}
		return result;
	}
652585
async def _dataobject_update_detect(self, _initialkeys, _savedresult):
        
        def expr(newvalues, updatedvalues):
            if any(v.getkey() in _initialkeys for v in updatedvalues if v is not None):
                return True
            else:
                return self.shouldupdate(newvalues, updatedvalues)
        while True:
            updatedvalues, _ = await multiwaitif(_savedresult, self, expr, True)
            if not self._updatedset:
                self.scheduler.emergesend(FlowUpdaterNotification(self, FlowUpdaterNotification.DATAUPDATED))
            self._updatedset.update(updatedvalues)
318788
synchronized int storeObject(JSONObject obj, Table table) {
        if (!this.belowMemThreshold()) {
            Logger.v("There is not enough space left on the device to store data, data discarded");
            return DB_OUT_OF_MEMORY_ERROR;
        }

        final String tableName = table.getName();

        Cursor cursor = null;
        int count = DB_UPDATE_ERROR;

        //noinspection TryFinallyCanBeTryWithResources
        try {
            final SQLiteDatabase db = dbHelper.getWritableDatabase();

            final ContentValues cv = new ContentValues();
            cv.put(KEY_DATA, obj.toString());
            cv.put(KEY_CREATED_AT, System.currentTimeMillis());
            db.insert(tableName, null, cv);
            cursor = db.rawQuery("SELECT COUNT(*) FROM " + tableName, null);
            cursor.moveToFirst();
            count = cursor.getInt(0);
        } catch (final SQLiteException e) {
            getConfigLogger().verbose("Error adding data to table " + tableName + " Recreating DB");

            if (cursor != null) {
                cursor.close();
                cursor = null;
            }
            dbHelper.deleteDatabase();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            dbHelper.close();
        }
        return count;
    }
408370
def _update_data(self, data, update_original=False, remove_missing=False):
        
        self._data.update(dict((key, self._deserialize(key, value))
                               for key, value in data.items()))

        # In certain situations, we want to treat missing keys as removals
        if remove_missing:
            for key in set(self._data.keys()) - set(data.keys()):
                self._data[key] = None

        if update_original:
            self._original_data = copy.deepcopy(self._data)
1349768
@Override
    public int executeUpdate(String updateSql) throws JdbcServerException {
        log.info("Received execute update request: " + updateSql);
        Message response = handleMessageAndCheckResponse(JdbcMessage.execute(updateSql));
        return Optional.ofNullable(
                response.getHeader(JdbcMessageHeaders.JDBC_ROWS_UPDATED))
                .map(Object::toString).map(Integer::valueOf)
                .orElse(0);
    }
546256
def insert(self, table, value, ignore=False, commit=True):
        
        value_q, _args = self._value_parser(value, columnname=False)
        _sql = ''.join(['INSERT', ' IGNORE' if ignore else '', ' INTO ', self._backtick(table),
                        ' (', self._backtick_columns(value), ') VALUES (', value_q, ');'])

        if self.debug:
            return self.cur.mogrify(_sql, _args)

        self.cur.execute(_sql, _args)
        if commit:
            self.conn.commit()
        return self.cur.lastrowid
421637
@Override
    public DaoResult createOrUpdate(T bo) {
        if (bo == null) {
            return null;
        }
        try (Connection conn = getConnection(upsertInTransaction)) {
            return createOrUpdate(conn, bo);
        } catch (SQLException e) {
            throw new DaoException(e);
        }
    }
511539
@Override
	public final int executeUpdate() throws SQLException {
		Split split = prepare();
		try {
			return stmt.executeUpdate();
		} finally {
			finish(split);
		}
	}
1285403
def insert(self, **data):
        
        if self.where_clause:
            raise Invalid("Cannot insert with 'where' clause.")
        # Ensure that order is preserved
        data = data.items()
        cmd = "insert into {table} ({attrs}) values ({values})".format(
            table=self.table_name,
            attrs=", ".join(entry[0] for entry in data),
            values=", ".join(["?"] * len(data)),
        )
        handle = Repo.db.execute(cmd, [entry[1] for entry in data])
        # Return the id of the added row
        return handle.lastrowid
1228624
String createInsertPreparedSQLStatement(D6Inex includeExcludeColumnNames,boolean ignoreDuplicate) {

        final Set<String> columnNameSet = getAllColumnNames();

        final StringGrabber sgSQL = new StringGrabber();

        // Get the table name
        final DBTable table = mModelClazz.getAnnotation(DBTable.class);
        final String tableName = table.tableName();

        if(ignoreDuplicate){
        	sgSQL.append("INSERT IGNORE INTO " + tableName + " (");
        }else{
        sgSQL.append("INSERT INTO " + tableName + " (");
        }
        final StringGrabber sgColumnNames = new StringGrabber();
        final StringGrabber sgValues = new StringGrabber();

        if (includeExcludeColumnNames != null) {
            includeExcludeColumnNames.manipulate(columnNameSet);
        }

        for (String columnName : columnNameSet) {

            final D6ModelClassFieldInfo fieldInfo = getFieldInfo(columnName);

            //
            final boolean isAutoIncrement = fieldInfo.isAutoIncrement;

            if (isAutoIncrement == false) {
                // - if auto increment is off
                sgColumnNames.append(columnName);
                sgColumnNames.append(", ");
                sgValues.append("?");
                sgValues.append(", ");
            } else {
                // - if auto increment is available
                // it's not the target of the update
            }

        }// end for

        if (sgColumnNames.length() > 2) {
            sgColumnNames.removeTail(2);
        }
        if (sgValues.length() > 2) {
            sgValues.removeTail(2);
        }

        sgSQL.append(sgColumnNames.toString());
        sgSQL.append(") ");
        sgSQL.append("VALUES ( ");
        sgSQL.append(sgValues.toString());
        sgSQL.append(" )");

        final String sql = sgSQL.toString();

        log("#createInsertPreparedSQLStatement sql=" + sql);

        return sql;
    }
294309
public PreparedStatement getDeleteStatement(ClassDescriptor cld) throws PersistenceBrokerSQLException, PersistenceBrokerException
    {
        try
        {
            return cld.getStatementsForClass(m_conMan).getDeleteStmt(m_conMan.getConnection());
        }
        catch (SQLException e)
        {
            throw new PersistenceBrokerSQLException("Could not build statement ask for", e);
        }
        catch (LookupException e)
        {
            throw new PersistenceBrokerException("Used ConnectionManager instance could not obtain a connection", e);
        }
    }
294837
def _handle_upsert(self, parts, unwritten_lobs=()):
        """"""
        self.description = None
        self._received_last_resultset_part = True  # set to 'True' so that cursor.fetch*() returns just empty list

        for part in parts:
            if part.kind == part_kinds.ROWSAFFECTED:
                self.rowcount = part.values[0]
            elif part.kind in (part_kinds.TRANSACTIONFLAGS, part_kinds.STATEMENTCONTEXT, part_kinds.PARAMETERMETADATA):
                pass
            elif part.kind == part_kinds.WRITELOBREPLY:
                # This part occurrs after lobs have been submitted not at all or only partially during an insert.
                # In this case the parameter part of the Request message contains a list called 'unwritten_lobs'
                # with LobBuffer instances.
                # Those instances are in the same order as 'locator_ids' received in the reply message. These IDs
                # are then used to deliver the missing LOB data to the server via WRITE_LOB_REQUESTs.
                for lob_buffer, lob_locator_id in izip(unwritten_lobs, part.locator_ids):
                    # store locator_id in every lob buffer instance for later reference:
                    lob_buffer.locator_id = lob_locator_id
                self._perform_lob_write_requests(unwritten_lobs)
            else:
                raise InterfaceError("Prepared insert statement response, unexpected part kind %d." % part.kind)
        self._executed = True
728175
@Override
    public synchronized int executeUpdate(final String query) throws DatabaseEngineException {
        Statement s = null;
        try {
            getConnection();
            s = conn.createStatement();
            return s.executeUpdate(query);
        } catch (final Exception ex) {
            throw new DatabaseEngineException("Error handling native query", ex);
        } finally {
            if (s != null) {
                try {
                    s.close();
                } catch (final Exception e) {
                    logger.trace("Error closing statement.", e);
                }
            }
        }
    }
555808
public int insertOrUpdate(Connection conn, Entity record, String... keys) throws SQLException {
		final Entity where = record.filter(keys);
		if(MapUtil.isNotEmpty(where) && count(conn, where) > 0) {
			return update(conn, record, where);
		}else {
			return insert(conn, record);
		}
	}
786903
def _todo_do_update(self, line):
        ""
        table, line = self.get_table_params(line)
        hkey, line = line.split(" ", 1)
        expected, attr = self.get_expected(line)

        if attr[0] == '-':
            op, attr = attr.split(" ", 1)
            op = op[1]
        else:
            op = "u"

        if attr[0] == '+':
            ret, attr = attr.split(" ", 1)
            ret = ret[1:]
        else:
            ret = "ALL_NEW"

        if ',' in hkey:
            hkey, rkey = hkey.split(",", 1)
        else:
            rkey = None

        item = table.new_item(hash_key=self.get_typed_key_value(table, hkey), range_key=self.get_typed_key_value(table, rkey, False))

        attr = json.loads(attr.strip())
        for name in attr.keys():
            value = attr[name]
            if isinstance(value, list):
                value = set(value)

            if op == 'a':
                item.add_attribute(name, value)
            elif op == 'd':
                item.delete_attribute(name, value)
            else:
                item.put_attribute(name, value)

        self.pprint(item)
        updated = item.save(expected_value=expected or None, return_values=ret)
        self.pprint(updated)

        if self.consumed:
            print "consumed units:", item.consumed_units