Sync execute SQL query, `allow_sync` must be set to True.
972407
def execute_sql(self, *args, **kwargs):
        
        assert self._allow_sync, (
            "Error, sync query is not allowed! Call the `.set_allow_sync()` "
            "or use the `.allow_sync()` context manager.")
        if self._allow_sync in (logging.ERROR, logging.WARNING):
            logging.log(self._allow_sync,
                        "Error, sync query is not allowed: %s %s" %
                        (str(args), str(kwargs)))
        return super().execute_sql(*args, **kwargs)
72631
def query(self, sql):
        '''
        
        '''
        try:
            self.connect()
            with self.con.cursor() as cursor:
                cursor.execute(sql)
                self.con.commit()
                res = cursor.fetchall()
                return res
        except Exception as e:
            print(e)
            return -1
        finally:
            self.close()
104840
def execute_and_auto_confirm(sql, name = nil)

      begin
        @connection.execute_update "call qsys.qcmdexc('QSYS/CHGJOB INQMSGRPY(*SYSRPYL)',0000000031.00000)"
        @connection.execute_update "call qsys.qcmdexc('ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY(''I'')',0000000045.00000)"
      rescue Exception => e
        raise "Could not call CHGJOB INQMSGRPY(*SYSRPYL) and ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY('I').\n" +
              "Do you have authority to do this?\n\n#{e.inspect}"
      end

      begin
        result = execute(sql, name)
      rescue Exception
        raise
      else
        # Return if all work fine
        result
      ensure

        # Ensure default configuration restoration
        begin
          @connection.execute_update "call qsys.qcmdexc('QSYS/CHGJOB INQMSGRPY(*DFT)',0000000027.00000)"
          @connection.execute_update "call qsys.qcmdexc('RMVRPYLE SEQNBR(9876)',0000000021.00000)"
        rescue Exception => e
          raise "Could not call CHGJOB INQMSGRPY(*DFT) and RMVRPYLE SEQNBR(9876).\n" +
                    "Do you have authority to do this?\n\n#{e.inspect}"
        end

      end
    end
1022107
def db_exec(self, query, args=None):
        
        if args is None:
            self.db_query(query)
        else:
            self.db_query(query, args)

        self.db.commit()
854801
def query(self, sql, param=None, stream=False, row_tuples=False):
        
        if not self.cursor:  # ALLOW NON-TRANSACTIONAL READS
            Log.error("must perform all queries inside a transaction")
        self._execute_backlog()

        try:
            if param:
                sql = expand_template(sql, quote_param(param))
            sql = self.preamble + outdent(sql)
            self.debug and Log.note("Execute SQL:\n{{sql}}", sql=indent(sql))

            self.cursor.execute(sql)
            if row_tuples:
                if stream:
                    result = self.cursor
                else:
                    result = wrap(list(self.cursor))
            else:
                columns = [utf8_to_unicode(d[0]) for d in coalesce(self.cursor.description, [])]
                if stream:
                    result = (wrap({c: utf8_to_unicode(v) for c, v in zip(columns, row)}) for row in self.cursor)
                else:
                    result = wrap([{c: utf8_to_unicode(v) for c, v in zip(columns, row)} for row in self.cursor])

            return result
        except Exception as e:
            e = Except.wrap(e)
            if "InterfaceError" in e:
                Log.error("Did you close the db connection?", e)
            Log.error("Problem executing SQL:\n{{sql|indent}}", sql=sql, cause=e, stack_depth=1)
370603
def execute(self, fetchcommand, sql, params=None):
		

		cur = self.conn.cursor()
		if params:
			if not type(params).__name__ == 'tuple':
				raise ValueError('the params argument needs to be a tuple')
				return None
			cur.execute(sql, params)
		else:
			cur.execute(sql)

		self.conn.commit()

		if not fetchcommand or fetchcommand == 'none':
			return

		if fetchcommand == 'last' or fetchcommand == 'lastid':
			lastdata = cur.fetchall()
			self.conn.commit()
			return lastdata

		m = insertion_pattern.match(sql)
		"""
		 TODO: This is a BUG - need to also check tail of query for RETURNING
		"""
		if m:
			""" lastid = cursor.fetchone()['lastval'] """
			lastdata = cur.fetchone()
			self.conn.commit()
			return lastdata

		if fetchcommand == 'fetchone' or fetchcommand == 'one':
			return cur.fetchone()
		elif fetchcommand == 'fetchall' or fetchcommand == 'all':
			return cur.fetchall()
		else:
			msg = "expecting <fetchcommand> argument to be either 'fetchone'|'one'|'fetchall|all'"
			raise ValueError(msg)
417657
def execQuery(self, sql, parameters = None, cursorClass = MySQLdb.cursors.Cursor, InnoDB = False):
		""""""
		i = 0
		errcode = 0
		caughte = None
		while i < self.numTries:
			i += 1
			try:	
				cursor = self.connection.cursor(cursorClass)
				if parameters:
					errcode = cursor.execute(sql, parameters)
				else:
					errcode = cursor.execute(sql)
				if InnoDB:
					self.connection.commit()
				results = cursor.fetchall()
				self.lastrowid = int(cursor.lastrowid)
				cursor.close()
				return results
			except MySQLdb.OperationalError, e:
				errcode = e[0]
				# errcodes of 2006 or 2013 usually indicate a dropped connection  
				# errcode 1100 is an error with table locking
				print(e)
				self.connection.ping(True)
				caughte = e
				continue
			except:				
				traceback.print_exc()
				break
		
		sys.stderr.write("\nSQL execution error in query at %s:" % datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
		sys.stderr.write("\n %s." % sql)
		sys.stderr.flush()
		sys.stderr.write("\nErrorcode: '%s'.\n" % (str(caughte)))
		sys.stderr.flush()
		raise MySQLdb.OperationalError(caughte)
471715
public function executeSQL($key, $query, $disable_foreign_key_checks = true, $entity=null)
    {
        if ($entity !== null && $entity != $this->last_entity) {
            $this->log("------------------------------------------------------");
            $this->log("Entity: '$entity'");
            $this->log("------------------------------------------------------");
            $this->last_entity = $entity;
        }

        $this->log(" * Sync::executeSQL '$key'...");

        $total_time_start = microtime(true);

        if ($disable_foreign_key_checks) {
            $this->adapter->query('set foreign_key_checks=0');
            $this->log("  * FK : Foreign key check disabled");
        }

        try {
            $time_start = microtime(true);
            $result = $this->adapter->query($query, ZendDb::QUERY_MODE_EXECUTE);
            $affected_rows = $result->getAffectedRows();

            // Log stuffs
            $time_stop = microtime(true);
            $time = number_format(($time_stop - $time_start), 2);
            $formatted_query = preg_replace('/(\n)|(\r)|(\t)/', ' ', $query);
            $formatted_query = preg_replace('/(\ )+/', ' ', $formatted_query);
            $this->log("  * SQL: " . substr(trim($formatted_query), 0, 70) . '...') ;
            $this->log("  * SQL: Query time $time sec(s))");
        } catch (\Exception $e) {
            $err = $e->getMessage();
            $msg = "Error running query ({$err}) : \n--------------------\n$query\n------------------\n";
            $this->log("[+] $msg\n");
            if ($disable_foreign_key_checks) {
                $this->log("[Error] Error restoring foreign key checks");
                $this->adapter->query('set foreign_key_checks=1');
            }
            throw new \Exception($msg);
        }

        if ($disable_foreign_key_checks) {
            $time_start = microtime(true);
            $this->adapter->query('set foreign_key_checks=1');
            $time_stop = microtime(true);
            $time = number_format(($time_stop - $time_start), 2);
            $this->log("  * FK : Foreign keys restored");
        }
        $time_stop = microtime(true);
        $time = number_format(($time_stop - $total_time_start), 2);
        $this->log(" * Time: $time secs, affected rows $affected_rows.");
    }
433188
def execute(self, stmt, **params):
        
        return self.session.execute(sql.text(stmt, bind=self.bind), **params)
186113
public SyncStatement request( Collection<? extends BEvent> toRequest ) {
        return new SyncStatement(getBthread(), toRequest, getWaitFor(), getBlock(), getInterrupt(), isHot(), getData());
    }
629842
protected void executeQueryPrologue(boolean isBatch) throws SQLException {
    executing = true;
    if (closed) {
      throw new SQLException("execute() is called on closed statement");
    }
    protocol.prolog(maxRows, protocol.getProxy() != null, connection, this);
    if (queryTimeout != 0 && (!canUseServerTimeout || isBatch)) {
      setTimerTask(isBatch);
    }
  }
650434
private void execute(String sql) throws SQLException {
        Statement statement = connection.createStatement();
        try {
            statement.executeUpdate(substitute(sql));
        } finally {
            DbUtils.closeQuietly(statement);
        }
    }
525977
function execute(req, res) {
  // TODO: ensure a conflict is triggered on all watched keys
  req.db.flushdb();
  res.send(null, Constants.OK);
}
325779
public static function sync(bbn\db $db, $dbs='', $dbs_table='', $num_try = 0){

    if ( !$num_try ){
      self::def($dbs, $dbs_table);
      self::first_call();
      self::disable();
      $mode_db = self::$db->get_error_mode();
      $mode_dbs = self::$dbs->get_error_mode();
      self::$db->set_error_mode("continue");
      self::$dbs->set_error_mode("continue");
    }

    $num_try++;

    $to_log = [
      'deleted_sync' => 0,
      'deleted_real' => 0,
      'updated_sync' => 0,
      'updated_real' => 0,
      'inserted_sync' => 0,
      'inserted_real' => 0,
      'num_problems' => 0,
      'problems' => []
    ];


    $retry = false;

    $start = ( $test = self::$dbs->get_one("
      SELECT MIN(chrono)
      FROM ".self::$dbs->escape(self::$dbs_table)."
      WHERE db NOT LIKE ?
      AND state = 0",
      self::$db->current) ) ? $test : time();
    // Deleting the entries prior to this sync we produced and have been seen by the twin process
    $to_log['deleted_sync'] = self::$dbs->delete(self::$dbs_table, [
      ['db', '=', self::$db->current],
      ['state', '=', 1],
      ['chrono', '<', $start]
    ]);

    // Selecting the entries inserted
    $ds = self::$dbs->rselect_all(self::$dbs_table, ['id', 'tab', 'vals', 'chrono'], [
      ['db', '!=', self::$db->current],
      ['state', '=', 0],
      ['action', '=', 'insert']
    ], [
      'chrono' => 'ASC',
      'id' => 'ASC'
    ]);
    // They just have to be inserted
    foreach ( $ds as $i => $d ){
      if ( isset(self::$methods['cbf1']) ){
        self::cbf1($d);
      }
      $vals = \bbn\x::json_base64_decode($d['vals']);
      if ( !\is_array($vals) ){
        $to_log['num_problems']++;
        $to_log['problems'][] = "Hey, look urgently at the row $d[id]!";
      }
      else if ( self::$db->insert($d['tab'], $vals) ){
        if ( isset(self::$methods['cbf2']) ){
          self::cbf2($d);
        }
        $to_log['inserted_sync']++;
        self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]);
      }
      else if ( self::$db->select($d['tab'], [], $vals) ){
        self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]);
      }
      else{
        if ( $num_try > self::$max_retry ){
          $to_log['num_problems']++;
          $to_log['problems'][] = "Problem while syncing (insert), check data with status 5 and ID ".$d['id'];
          self::$dbs->update(self::$dbs_table, ["state" => 5], ["id" => $d['id']]);
        }
        $retry = 1;
      }
    }


    // Selecting the entries modified and deleted in the twin DB,
    // ordered by table and rows (so the same go together)
    $ds = self::$dbs->rselect_all(self::$dbs_table, ['id', 'tab', 'action', 'rows', 'vals', 'chrono'], [
      ['db', '!=', self::$db->current],
      ['state', '=', 0],
      ['rows', '!=', '[]'],
      ['action', '!=', 'insert']
    ], [
      'tab' => 'ASC',
      'rows' => 'ASC',
      'chrono' => 'ASC',
      'id' => 'ASC'
    ]);
    foreach ( $ds as $i => $d ){
      // Executing the first callback
      $d['rows'] = bbn\x::json_base64_decode($d['rows']);
      $d['vals'] = bbn\x::json_base64_decode($d['vals']);
      if ( isset(self::$methods['cbf1']) ){
        self::cbf1($d);
      }
      // Proceeding to the actions: delete is before
      if ( strtolower($d['action']) === 'delete' ){
        if ( self::$db->delete($d['tab'], $d['rows']) ){
          self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]);
          $to_log['deleted_real']++;
        }
        else if ( !self::$db->select($d['tab'], [], $d['rows']) ){
          self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]);
        }
        else{
          if ( $num_try > self::$max_retry ){
            self::$dbs->update(self::$dbs_table, ["state" => 5], ["id" => $d['id']]);
            $to_log['num_problems']++;
            $to_log['problems'][] = "Problem while syncing (delete), check data with status 5 and ID ".$d['id'];
          }
          $retry = 1;
        }
      }
      // Checking if there is another change done to this record and when in the twin DB
      $next_time = (
              isset($ds[$i+1]) &&
              ($ds[$i+1]['tab'] === $d['tab']) &&
              ($ds[$i+1]['rows'] === $d['rows'])
            ) ? $ds[$i+1]['chrono'] : microtime();
      // Looking for the actions done on this specific record in our database
      // between the twin change and the next (or now if there is no other change)
      $each = self::$dbs->rselect_all(self::$dbs_table, ['id', 'chrono', 'action', 'vals'], [
        ['db', '=', self::$db->current],
        ['tab', '=', $d['tab']],
        ['rows', '=', $d['rows']],
        ['chrono', '>=', $d['chrono']],
        ['chrono', '<', $next_time],
      ]);
      if ( \count($each) > 0 ){
        $to_log['num_problems']++;
        $to_log['problems'][] = "Conflict!";
        $to_log['problems'][] = $d;
        foreach ( $each as $e ){
          // If it's deleted locally and updated on the twin we restore
          if ( strtolower($e['action']) === 'delete' ){
            if ( strtolower($d['action']) === 'update' ){
              if ( !self::$db->insert_update(
                      $d['tab'],
                      bbn\x::merge_arrays(
                        $e['vals'],
                        $d['vals']
                      ))
              ){
                $to_log['num_problems']++;
                $to_log['problems'][] = "insert_update number 1 had a problem";
              }
            }
          }
          // If it's updated locally and deleted in the twin we restore
          else if ( strtolower($e['action']) === 'update' ){
            if ( strtolower($d['action']) === 'delete' ){
              if ( !self::$db->insert_update($d['tab'], bbn\x::merge_arrays($d['vals'], $e['vals'])) ){
                $to_log['num_problems']++;
                $to_log['problems'][] = "insert_update had a problem";
              }
            }
          // If it's updated locally and in the twin we merge the values for the update
            else if ( strtolower($d['action']) === 'update' ){
              $d['vals'] = bbn\x::merge_arrays($d['vals'], $e['vals']);
            }
          }
        }
      }
      // Proceeding to the actions update is after in case we needed to restore
      if ( strtolower($d['action']) === 'update' ){
        if ( self::$db->update($d['tab'], $d['vals'], $d['rows']) ){
          self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]);
          $to_log['updated_real']++;
        }
        else if ( self::$db->select($d['tab'], [], bbn\x::merge_arrays($d['rows'], $d['vals'])) ){
          self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]);
        }
        else{
          if ( $num_try > self::$max_retry ){
            self::$dbs->update(self::$dbs_table, ["state" => 5], ["id" => $d['id']]);
            $to_log['num_problems']++;
            $to_log['problems'][] = "Problem while syncing (update), check data with status 5 and ID ".$d['id'];
          }
          $retry = 1;
        }
      }
      // Callback number 2
      if ( isset(self::$methods['cbf2']) ){
        self::cbf2($d);
      }
    }


    $res = [];
    foreach ( $to_log as $k => $v ){
      if ( !empty($v) ){
        $res[$k] = $v;
      }
    }
    if ( $retry && ( $num_try <= self::$max_retry ) ){
      $res = bbn\x::merge_arrays($res, self::sync($db, $dbs, $dbs_table, $num_try));
    }
    else{
      self::$db->set_error_mode($mode_db);
      self::$dbs->set_error_mode($mode_dbs);
      self::enable();
    }
    return $res;
  }
668025
def execute(self, operation, parameters=None, is_response=True):
        
        if parameters is None or not parameters:
            sql = operation
        else:
            sql = operation % _escaper.escape_args(parameters)

        self._reset_state()

        self._state = self._STATE_RUNNING
        self._uuid = uuid.uuid1()

        if is_response:
            response = self._db.select(sql, settings={'query_id': self._uuid})
            self._process_response(response)
        else:
            self._db.raw(sql)
819284
async def _run_sql(database, operation, *args, **kwargs):
    
    __log__.debug((operation, args, kwargs))

    with peewee.__exception_wrapper__:
        cursor = await database.cursor_async()

        try:
            await cursor.execute(operation, *args, **kwargs)
        except:
            await cursor.release()
            raise

        return cursor
1101490
async def execute(self, sql: str, parameters: Iterable[Any] = None) -> None:
        """"""
        if parameters is None:
            parameters = []
        await self._execute(self._cursor.execute, sql, parameters)