Execute the sql at the first time of the module installation.
344313
private static function setupModule()
    {
        // Check if ddmedia table was already created, if not create it.
        if (!self::tableExists('ddmedia')) {
            self::executeSQL(self::$_sCreateDdMediaSql);
        }
        // Check if ddmedia table has all needed fields, if not add them to the table.
        foreach (self::$_aSetupDdMediaSQLs as $sField => $sSql) {
            if (!self::fieldExists($sField, 'ddmedia')) {
                self::executeSQL($sSql);
            }
        }
        /** @var \OxidEsales\Eshop\Core\Config $oConfig */
        $oConfig = Registry::getConfig();
        $oConfig->saveShopConfVar('bool', 'blModuleWasEnabled', 'true', $oConfig->getShopId(), 'module:ddoewysiwyg');
    }
1052933
public void execute()
        throws InstallationException
    {
        Instance instance = searchInstance();
        if (instance == null) {
            instance = createInstance();
        }
        updateDB(instance);
    }
1269673
def execute(self, sql, parameters=None, bulk_parameters=None):
        
        if self.connection._closed:
            raise ProgrammingError("Connection closed")

        if self._closed:
            raise ProgrammingError("Cursor closed")

        self._result = self.connection.client.sql(sql, parameters,
                                                  bulk_parameters)
        if "rows" in self._result:
            self.rows = iter(self._result["rows"])
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
1060781
async def setup(self):
        """"""
        try:
            engine = await self.db
            created = False
            if not await engine.has_table(self.table_name):
                # create table
                logger.info("Creating SQL table [{}]".format(self.table_name))
                items = self._get_table()
                await engine.execute(CreateTable(items))
                # create indeces
                conn = await engine.connect()
                await conn.execute(
                    "CREATE INDEX `lb_last_updated` ON `{}` (`source_id` DESC,`updated` DESC);".format(self.table_name))
                await conn.execute(
                    "CREATE INDEX `lb_post` ON `{}` (`target_id` DESC,`post_id` DESC);".format(self.table_name))
                await conn.close()
                created = True
            # create control table if not already created.
            if self.control_table_name and not await engine.has_table(self.control_table_name):
                # create table
                logger.info("Creating SQL control table [{}]".format(self.control_table_name))
                items = self._get_control_table()
                await engine.execute(CreateTable(items))
                created = True
            return created
        except Exception as exc:
            logger.error("[DB] Error when setting up SQL table: {}".format(exc))
        return False
828714
public void execute() {
        try {
            new JdbcTemplate(dataSource).execute(readResourceContent(SCHEMA_FILE)); // TODO: sql independence
        } catch (IOException e) {
            throw new RuntimeException("Could not create schema for EDBI Index", e);
        }
    }
762749
def init():
    
    global _users, _names
    _configure_app(app)
    _users, _names = _init_login_manager(app)
    _configure_logger()
    init_scheduler(app.config.get('SQLALCHEMY_DATABASE_URI'))
    db.init(app.config.get('SQLALCHEMY_DATABASE_URI'))
272138
public void runSql( String sql ) throws Exception {
        String[] sqlSplit = sql.split("\n");
        StringBuilder sb = new StringBuilder();
        for( String string : sqlSplit ) {
            String trim = string.trim();
            if (trim.length() == 0) {
                continue;
            }
            if (trim.startsWith("--")) {
                continue;
            }
            sb.append(trim + " ");
        }

        String[] sqls = sb.toString().split(";");
        for( String single : sqls ) {
            executeInsertUpdateDeleteSql(single);
        }
    }
960988
def init_functions(connection):
    """"""
    if settings.CFG["db"]["create_functions"]:
        print("Refreshing SQL functions...")
        for file in path.template_files("../sql/", exts=[".sql"]):
            func = sa.DDL(path.template_str(file))
            LOG.info("Loading: '%s' into database", file)
            connection.execute(func)
            connection.commit()
913875
public function install()
    {
        define('GL_INSTALL', true);
        $this->init();
        echo '<pre>';
        $fail = false;
        $db = new DatabaseManager();
        if ($db->connectAndSelect()) {
            $this->setDatabase($db);
            $this->log('Connection to database ok');

            $this->log('Installing Database...');
            $models = $this->getModels();
            foreach ($models as $model) {
                $instance = new $model(null);
                if ($instance instanceof Model) {
                    $diff = $instance->getStructureDifferences($db, isset($_GET['drop']));
                    $this->log('Installing table \'' . $instance->getTableName() . '\' generated by ' . get_class($instance) . '...',
                        2);
                    foreach ($diff as $action) {
                        $this->log('Action: ' . $action['sql'] . '...', 3, false);

                        if (isset($_GET['exec'])) {
                            try {
                                DBStructure::runAction($db, $instance, $action);
                                $this->log('[OK]', 0);
                            } catch (\Exception $ex) {
                                $this->log('[FAIL]', 0);
                                $fail = true;
                            }
                        }
                        echo "\n";
                    }
                }
            }
            if (!isset($_GET['exec'])) {
                $this->log('Please <a href="?exec">click here</a> to make this changes in the database.');
            } else {
                $db2 = new DBStructure();
                $db2->setDatabaseUpdate();
                $this->log('All done site ready for develop/production!');
            }
        } else {
            if ($db->getConnection() !== null) {
                if (isset($_GET['create_database'])) {
                    if ($db->exec('CREATE DATABASE ' . $this->config['database']['database'])) {
                        echo 'Database created successful! Please reload the navigator';
                    } else {
                        echo 'Can not create the database!';
                    }
                } else {
                    echo 'Can\'t select the database <a href="install.php?create_database">Try to create database</a>';
                }
            } else {
                echo 'Cannot connect to database';
            }
        }
    }
1141583
def init_app(self, app):
        """"""
        assert 'zodb' not in app.extensions, \
               'app already initiated for zodb'
        app.extensions['zodb'] = _ZODBState(self, app)
        app.teardown_request(self.close_db)
1099221
public function install()
    {
        $sql = 'CREATE TABLE IF NOT EXISTS `'.self::TABLENAME.'` (`id` varchar(32) NOT NULL, PRIMARY KEY (`id`), `session_data` longtext NULL, `access` int(10) NULL);';

        return $this->app['db']
            ->raw($sql)
            ->execute() instanceof PDOStatement;
    }
776875
def execute(self, conn, app, release_version, pset_hash, output_label, global_tag, transaction = False):
        
        binds = {}
        binds["app_name"]=app
        binds["release_version"]=release_version
        binds["pset_hash"]=pset_hash
        binds["output_module_label"]=output_label
        binds["global_tag"]=global_tag

        result = self.dbi.processData(self.sql, binds, conn, transaction)

        plist = self.formatDict(result)

	if len(plist) < 1: return -1
        return plist[0]["output_mod_config_id"]
278475
public function execute()
	{
		$this->connect();

		// Take a local copy so that we don't modify the original query and cause issues later
		$sql = $this->replacePrefix((string) $this->sql);

		$count = $this->getCount();

		// Increment the query counter.
		$this->count++;

		// If debugging is enabled then let's log the query.
		if ($this->debug)
		{
			// Add the query to the object queue.
			$this->log(
				Log\LogLevel::DEBUG,
				'{sql}',
				array('sql' => $sql, 'category' => 'databasequery', 'trace' => debug_backtrace())
			);
		}

		// Reset the error values.
		$this->errorNum = 0;
		$this->errorMsg = '';

		// Bind the variables
		if ($this->sql instanceof PreparableInterface)
		{
			$bounded =& $this->sql->getBounded();

			if (\count($bounded))
			{
				// Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost.
				$this->cursor = @pg_execute($this->connection, $this->queryName . $count, array_values($bounded));
			}
			else
			{
				// Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost.
				$this->cursor = @pg_query($this->connection, $sql);
			}
		}
		else
		{
			// Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost.
			$this->cursor = @pg_query($this->connection, $sql);
		}

		// If an error occurred handle it.
		if (!$this->cursor)
		{
			// Check if the server was disconnected.
			if (!$this->connected())
			{
				try
				{
					// Attempt to reconnect.
					$this->connection = null;
					$this->connect();
				}
				catch (ConnectionFailureException $e)
				{
					// If connect fails, ignore that exception and throw the normal exception.
					$this->errorMsg = pg_last_error($this->connection);

					// Only get an error number if we have a non-boolean false cursor, otherwise use default 0
					if ($this->cursor !== false)
					{
						$this->errorNum = (int) pg_result_error_field($this->cursor, PGSQL_DIAG_SQLSTATE);
					}

					// Throw the normal query exception.
					$this->log(
						Log\LogLevel::ERROR,
						'Database query failed (error #{code}): {message}; Failed query: {sql}',
						array('code' => $this->errorNum, 'message' => $this->errorMsg, 'sql' => $sql)
					);

					throw new ExecutionFailureException($sql, $this->errorMsg, $this->errorNum);
				}

				// Since we were able to reconnect, run the query again.
				return $this->execute();
			}

			// The server was not disconnected.
			$this->errorNum = (int) pg_result_error_field($this->cursor, PGSQL_DIAG_SQLSTATE);
			$this->errorMsg = pg_last_error($this->connection);

			// Throw the normal query exception.
			$this->log(
				Log\LogLevel::ERROR,
				'Database query failed (error #{code}): {message}; Failed query: {sql}',
				array('code' => $this->errorNum, 'message' => $this->errorMsg, 'sql' => $sql)
			);

			throw new ExecutionFailureException($sql, $this->errorMsg, $this->errorNum);
		}

		return $this->cursor;
	}
1213952
def init_db(self, app, entry_point_group='invenio_db.models', **kwargs):
        """"""
        # Setup SQLAlchemy
        app.config.setdefault(
            'SQLALCHEMY_DATABASE_URI',
            'sqlite:///' + os.path.join(app.instance_path, app.name + '.db')
        )
        app.config.setdefault('SQLALCHEMY_ECHO', False)

        # 
        database = kwargs.get('db', db)
        database.init_app(app)

        # Initialize versioning support.
        self.init_versioning(app, database, kwargs.get('versioning_manager'))

        # Initialize model bases
        if entry_point_group:
            for base_entry in pkg_resources.iter_entry_points(
                    entry_point_group):
                base_entry.load()

        # All models should be loaded by now.
        sa.orm.configure_mappers()
        # Ensure that versioning classes have been built.
        if app.config['DB_VERSIONING']:
            manager = self.versioning_manager
            if manager.pending_classes:
                if not versioning_models_registered(manager, database.Model):
                    manager.builder.configure_versioned_classes()
            elif 'transaction' not in database.metadata.tables:
                manager.declarative_base = database.Model
                manager.create_transaction_model()
                manager.plugins.after_build_tx_class(manager)
73369
synchronized protected void install() throws ManagedProcessException {
        try {
            ManagedProcess mysqlInstallProcess = installPreparation();
            mysqlInstallProcess.start();
            mysqlInstallProcess.waitForExit();
        } catch (Exception e) {
            throw new ManagedProcessException("An error occurred while installing the database", e);
        }
        logger.info("Installation complete.");
    }
517459
def install_sql_hook():
    # type: () -> None
    """"""
    try:
        from django.db.backends.utils import CursorWrapper  # type: ignore
    except ImportError:
        from django.db.backends.util import CursorWrapper  # type: ignore

    try:
        real_execute = CursorWrapper.execute
        real_executemany = CursorWrapper.executemany
    except AttributeError:
        # This won't work on Django versions < 1.6
        return

    def record_many_sql(sql, param_list, cursor):
        for params in param_list:
            record_sql(sql, params, cursor)

    def execute(self, sql, params=None):
        try:
            return real_execute(self, sql, params)
        finally:
            record_sql(sql, params, self.cursor)

    def executemany(self, sql, param_list):
        try:
            return real_executemany(self, sql, param_list)
        finally:
            record_many_sql(sql, param_list, self.cursor)

    CursorWrapper.execute = execute
    CursorWrapper.executemany = executemany
    ignore_logger("django.db.backends")