Run a SQL query as ignoring any constraint violations.
This allows idempotent inserts (equivalent to INSERT IGNORE).
496073
public static void runIgnoringConstraintViolation(Runnable task)
    {
        try {
            task.run();
        }
        catch (RuntimeException e) {
            if (!sqlCodeStartsWith(e, "23")) {
                throw e;
            }
        }
    }
1366475
void checkInsert(Session session, Table table, Object[] row) {

        switch (constType) {

            case CHECK :
                if (!isNotNull) {
                    checkCheckConstraint(session, table, row);
                }

                return;

            case FOREIGN_KEY :
                PersistentStore store =
                    session.sessionData.getRowStore(core.mainTable);

                if (ArrayUtil.hasNull(row, core.refCols)) {
                    if (core.matchType == OpTypes.MATCH_SIMPLE) {
                        return;
                    }

                    if (core.refCols.length == 1) {
                        return;
                    }

                    if (ArrayUtil.hasAllNull(row, core.refCols)) {
                        return;
                    }

                    // core.matchType == OpTypes.MATCH_FULL
                } else if (core.mainIndex.exists(session, store, row,
                                                 core.refCols)) {
                    return;
                } else if (core.mainTable == core.refTable) {

                    // special case: self referencing table and self referencing row
                    int compare = core.mainIndex.compareRowNonUnique(row,
                        core.refCols, row);

                    if (compare == 0) {
                        return;
                    }
                }

                String[] info = new String[] {
                    core.refName.name, core.mainTable.getName().name
                };

                throw Error.error(ErrorCode.X_23502, ErrorCode.CONSTRAINT,
                                  info);
        }
    }
116363
def _execute_simple_query(self, query):
        
        self._logger.info(u'Execute simple query: [{}]'.format(query))

        # All of the statements in the query are sent here in a single message
        self.connection.write(messages.Query(query))

        # The first response could be a number of things:
        #   ErrorResponse: Something went wrong on the server.
        #   EmptyQueryResponse: The query being executed is empty.
        #   RowDescription: This is the "normal" case when executing a query.
        #                   It marks the start of the results.
        #   CommandComplete: This occurs when executing DDL/transactions.
        self._message = self.connection.read_message()
        if isinstance(self._message, messages.ErrorResponse):
            raise errors.QueryError.from_error_response(self._message, query)
        elif isinstance(self._message, messages.RowDescription):
            self.description = [Column(fd, self.unicode_error) for fd in self._message.fields]
            self._message = self.connection.read_message()
            if isinstance(self._message, messages.ErrorResponse):
                raise errors.QueryError.from_error_response(self._message, query)
984642
def executemany(self, query, args):
        
        if not args:
            return

        m = RE_INSERT_VALUES.match(query)
        if m:
            q_prefix = m.group(1)
            q_values = m.group(2).rstrip()
            q_postfix = m.group(3) or ''
            assert q_values[0] == '(' and q_values[-1] == ')'
            yield self._do_execute_many(q_prefix, q_values, q_postfix, args,
                                        self.max_stmt_length,
                                        self._get_db().encoding)
        else:
            rows = 0
            for arg in args:
                yield self.execute(query, arg)
                rows += self.rowcount
            self.rowcount = rows
        raise gen.Return(self.rowcount)
1129433
protected void execute(String sqlStatement, PrintWriter out, boolean acceptFailure) throws Exception {

        try (Connection conn = dataSource.getConnection()) {
            try (Statement stmt = conn.createStatement()) {

                boolean success = execute(stmt, sqlStatement, out, acceptFailure);

                // Loop over all kinds of results.
                while (success) { /* 'success' is not modified below this line */
                    int rowCount = stmt.getUpdateCount();

                    if (rowCount > 0) {
                        // --------------------------------------------------
                        // Result of successful INSERT or UPDATE or the like
                        // --------------------------------------------------
                        if (options.debug) {
                            out.println("Rows affected: " + rowCount);
                            out.flush();
                        }

                        if (stmt.getMoreResults()) {
                            continue;
                        }

                    } else if (rowCount == 0) {
                        // --------------------------------------------------
                        // Either a DDL command or 0 updates
                        // --------------------------------------------------
                        if (options.debug) {
                            out.println("No rows affected or statement was DDL command");
                            out.flush();
                        }

                        boolean moreResults;
                        try {
                            moreResults = stmt.getMoreResults();
                        } catch (SQLException sqle) {

                            // State: 24000 - Invalid cursor state
                            //  [Teradata: Continue request submitted but no response to return]
                            if (sqle.getSQLState().startsWith("24")) {
                                break;

                            } else {
                                throw sqle;
                            }
                        }
                        if (moreResults) {
                            continue;
                        }

                    } else { // rowCount < 0
                        // --------------------------------------------------
                        // Either we have a result set or no more results...
                        // --------------------------------------------------
                        ResultSet rs = stmt.getResultSet();
                        if (null != rs) {
                            // Ignore resultset
                            rs.close();

                            if (stmt.getMoreResults()) {
                                continue;
                            }
                        }
                    }

                    // No more results
                    break;
                }
            }
        } catch (SQLException sqle) {
            out.println("Failed to execute statement: \n" + sqlStatement);
            out.println("\n\nDescription of failure: \n" + Database.squeeze(sqle));
            out.flush();
            throw sqle;

        } catch (Exception e) {
            out.println("Failed to execute statement: \n" + sqlStatement);
            out.println("\n\nDescription of failure: \n" + e.getMessage());
            out.flush();
            throw e;
        }
    }
767314
def execute(self, query, *parameters, **kwargs):
        """"""
        cursor = self._cursor()
        try:
            self._execute(cursor, query, parameters, kwargs)

        except:
            raise

        finally:
            cursor.close()
820079
def execute(cur, sql):
    
    command, verbose, arg = parse_special_command(sql)

    if (command not in COMMANDS) and (command.lower() not in COMMANDS):
        raise CommandNotFound

    try:
        special_cmd = COMMANDS[command]
    except KeyError:
        special_cmd = COMMANDS[command.lower()]
        if special_cmd.case_sensitive:
            raise CommandNotFound('Command not found: %s' % command)

    # "help <SQL KEYWORD> is a special case.
    if command == 'help' and arg:
        return show_keyword_help(cur=cur, arg=arg)

    if special_cmd.arg_type == NO_QUERY:
        return special_cmd.handler()
    elif special_cmd.arg_type == PARSED_QUERY:
        return special_cmd.handler(cur=cur, arg=arg, verbose=verbose)
    elif special_cmd.arg_type == RAW_QUERY:
        return special_cmd.handler(cur=cur, query=sql)
557485
def execute(self, query, params=None, cursor=None):
        
        conn = yield self._get_conn()
        try:
            cur = conn.cursor(cursor)
            yield cur.execute(query, params)
            yield cur.close()
        except:
            self._close_conn(conn)
            raise
        else:
            self._put_conn(conn)
        raise Return(cur)
81881
@Override
  public ResultSet executeQuery(String sql) throws SQLException
  {
    raiseSQLExceptionIfStatementIsClosed();
    return executeQueryInternal(sql, null);
  }
889582
def _before_insert(mapper, connection, target):
    """"""
    if target.position is None:
        func = sa.sql.func
        stmt = sa.select([func.coalesce(func.max(mapper.mapped_table.c.position), -1)])
        target.position = connection.execute(stmt).scalar() + 1
1060113
def execute(self, sql, parameters = None, cursorClass = DictCursor, quiet = False, locked = False, do_commit = True):
		""""""
		i = 0
		errcode = 0
		caughte = None
		cursor = None
		if sql.find(";") != -1 or sql.find("\\G") != -1:
			# Catches some injections
			raise Exception("The SQL command '%s' contains a semi-colon or \\G. This is a potential SQL injection." % sql)
		while i < self.numTries:
			i += 1
			try:
				assert(not(self.connection) or not(self.connection.open))
				self._get_connection(cursorClass)
				cursor = self.connection.cursor()
				if locked:
					cursor.execute(self.lockstring)
					self.locked = True
				if parameters:
					errcode = cursor.execute(sql, parameters)
				else:
					errcode = cursor.execute(sql)
				self.lastrowid = int(cursor.lastrowid)
				if do_commit and self.isInnoDB:
					self.connection.commit()
				results = cursor.fetchall()
				if locked:
					cursor.execute(self.unlockstring)
					self.locked = False
				cursor.close()
				self._close_connection()
				return results
			except MySQLdb.OperationalError, e:
				if cursor:
					if self.locked:
						cursor.execute(self.unlockstring)
						self.locked = False
					cursor.close()
				self._close_connection()
				caughte = str(e)
				errcode = e[0]
				continue
			except Exception, e:
				if cursor:
					if self.locked:
						cursor.execute(self.unlockstring)
						self.locked = False
					cursor.close()
				self._close_connection()
				caughte = str(e)
				traceback.print_exc()
				break
			sleep(0.2)
		
		if not quiet:
			sys.stderr.write("\nSQL execution error in query %s at %s:" % (sql, datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
			sys.stderr.write("\nErrorcode/Error: %d - '%s'.\n" % (errcode, str(caughte)))
			sys.stderr.flush()
		raise MySQLdb.OperationalError(caughte)
718990
def insert(table, datas, avoid_conflict=False):
        
        if avoid_conflict:
            debut = """INSERT INTO {table} {ENTETE_INSERT} VALUES {BIND_INSERT} ON CONFLICT DO NOTHING"""
        else:
            debut = """INSERT INTO {table} {ENTETE_INSERT} VALUES {BIND_INSERT} RETURNING *"""
        l = [abstractRequetesSQL.formate(debut, table=table, INSERT=d, args=d) for d in datas if d]
        return Executant(l)
63555
void enforceRowConstraints(Session session, Object[] data) {

        for (int i = 0; i < defaultColumnMap.length; i++) {
            Type type = colTypes[i];

            data[i] = type.convertToTypeLimits(session, data[i]);

            if (type.isDomainType()) {
                Constraint[] constraints =
                    type.userTypeModifier.getConstraints();

                for (int j = 0; j < constraints.length; j++) {
                    constraints[j].checkCheckConstraint(session, this,
                                                        data[i]);
                }
            }

            if (data[i] == null) {
                if (colNotNull[i]) {
                    Constraint c = getNotNullConstraintForColumn(i);

                    if (c == null) {
                        if (getColumn(i).isPrimaryKey()) {
                            c = this.getPrimaryConstraint();
                        }
                    }

                    String[] info = new String[] {
                        c.getName().name, tableName.name
                    };

                    throw Error.error(ErrorCode.X_23503, ErrorCode.CONSTRAINT,
                                      info);
                }
            }
        }
    }
1048076
public int executeUpdate(String sql) throws SQLException {
    if (executeInternal(sql, fetchSize, Statement.NO_GENERATED_KEYS)) {
      return 0;
    }
    return getUpdateCount();
  }
1206386
def execute_sql(self, query):
        
        c = self.con.cursor()
        c.execute(query)
        result = []
        if c.rowcount > 0:
            try:
                result = c.fetchall()
            except psycopg2.ProgrammingError:
                pass
        return result
272393
def insert(conn, qualified_name: str, column_names, records):
    """"""

    query = create_insert_statement(qualified_name, column_names)

    with conn:
        with conn.cursor(cursor_factory=NamedTupleCursor) as cursor:
            for record in records:
                cursor.execute(query, record)
1096441
def execute(self, sql, *args, **kwargs):
    '''
    
    '''
    try:
      self.cursor.execute(sql, *args)
    except self.sqlite3.InterfaceError, msg:
      raise self.sqlite3.InterfaceError(unicode(msg) + '\nTry converting types or pickling.')
    rows = self.cursor.fetchall()

    self.__commit_if_necessary(kwargs)

    if None == self.cursor.description:
      return None
    else:
      colnames = [d[0].decode('utf-8') for d in self.cursor.description]
      rawdata = [OrderedDict(zip(colnames,row)) for row in rows]
      return rawdata