Retrieve dictionary of insert statements to be executed.
507793
def _get_insert_commands(self, rows, cols):
        """"""
        # Get insert queries
        insert_queries = {}
        for table in tqdm(list(rows.keys()), total=len(list(rows.keys())), desc='Getting insert rows queries'):
            insert_queries[table] = {}
            _rows = rows.pop(table)
            _cols = cols.pop(table)

            if len(_rows) > 1:
                insert_queries[table]['insert_many'] = self.insert_many(table, _cols, _rows, execute=False)
            elif len(_rows) == 1:
                insert_queries[table]['insert'] = self.insert(table, _cols, _rows, execute=False)
        return insert_queries
1329529
def build_insert(table_name, attributes):
    
    sql = "INSERT INTO %s" %(table_name)
    column_str = u""
    value_str = u""
    for index, (key, value) in enumerate(attributes.items()):
        if index > 0:
            column_str += u","
            value_str += u","
        column_str += key
        value_str += value_to_sql_str(value)
    sql = sql + u"(%s) VALUES(%s)" %(column_str, value_str)
    return sql
981955
def create_insert():
    
    insert = upkey("insert").setResultsName("action")

    # VALUES
    attrs = Group(delimitedList(var)).setResultsName("attrs")
    value_group = Group(Suppress("(") + delimitedList(value) + Suppress(")"))
    values = Group(delimitedList(value_group)).setResultsName("list_values")
    values_insert = Suppress("(") + attrs + Suppress(")") + upkey("values") + values

    # KEYWORDS
    keyword = Group(var + Suppress("=") + value)
    item = Group(Suppress("(") + delimitedList(keyword) + Suppress(")"))
    keyword_insert = delimitedList(item).setResultsName("map_values")

    return insert + into + table + (values_insert | keyword_insert) + Optional(throttle)
464310
def _generateInsertStatement(self, dataset_name, cols):
        """"""
        col_names = [col["varname"] for col in cols]

        # Generate question mark placeholders
        qms = ','.join(['?' for x in col_names])

        return 'INSERT INTO %s (%s) values (%s)' % (dataset_name, ','.join(col_names), qms)
1020922
public List<Object> insertForGeneratedKeys(Connection conn, Entity record) throws SQLException {
		checkConn(conn);
		if(CollectionUtil.isEmpty(record)){
			throw new SQLException("Empty entity provided!");
		}
		
		PreparedStatement ps = null;
		try {
			ps = dialect.psForInsert(conn, record);
			ps.executeUpdate();
			return StatementUtil.getGeneratedKeys(ps);
		} catch (SQLException e) {
			throw e;
		} finally {
			DbUtil.close(ps);
		}
	}
556207
def insert(self, packet, **kwargs):
        ''' 

        '''
        values = [ ]
        pd     = packet._defn

        for defn in pd.fields:
            val = getattr(packet.raw, defn.name)

            if val is None and defn.name in pd.history:
                val = getattr(packet.history, defn.name)
            
            values.append(val)

        qmark = ['?'] * len(values)
        sql   = 'INSERT INTO %s VALUES (%s)' % (pd.name, ', '.join(qmark))


        self._conn.execute(sql, values)
17219
def insert_multiple_records(self,
                                table: str,
                                fields: Sequence[str],
                                records: Sequence[Sequence[Any]]) -> int:
        """"""
        self.ensure_db_open()
        sql = self.localize_sql(get_sql_insert(table, fields,
                                               self.get_delims()))
        log.debug("About to insert multiple records with SQL template: " + sql)
        try:
            cursor = self.db.cursor()
            debug_sql(sql, records)
            cursor.executemany(sql, records)
            # ... binds the placeholders (?, %s) to values in the process
            # http://www.python.org/dev/peps/pep-0249/
            log.debug("Records inserted.")
            return cursor.rowcount
        except:  # nopep8
            log.exception("insert_multiple_records: Failed to insert records.")
            raise
301274
def insert_object_into_db_pk_unknown(self,
                                         obj: Any,
                                         table: str,
                                         fieldlist: Sequence[str]) -> None:
        """"""
        self.ensure_db_open()
        valuelist = []
        for f in fieldlist[1:]:
            valuelist.append(getattr(obj, f))
        cursor = self.db.cursor()
        self.db_exec_with_cursor(
            cursor,
            get_sql_insert_without_first_field(table, fieldlist,
                                               self.get_delims()),
            *valuelist
        )
        pkvalue = get_pk_of_last_insert(cursor)
        setattr(obj, fieldlist[0], pkvalue)
829641
def transaction_insert_dict_auto_inc(self, transaction_cursor, tblname, d, unique_id_fields = [], fields = None, check_existing = False, id_field = 'ID'):
        ''''''
        sql, params, record_exists = self.create_insert_dict_string(tblname, d, PKfields=unique_id_fields, fields=fields, check_existing = check_existing)
        if not record_exists:
            transaction_cursor.execute(sql, params)
        id = transaction_cursor.lastrowid
        if id == None:
            id = self.get_unique_record('SELECT * FROM {0} WHERE {1}'.format(tblname, ' AND '.join([f + '=%s' for f in unique_id_fields])), parameters = tuple([d[f] for f in unique_id_fields]))[id_field]
        assert(id)
        return id
773392
def insert_many(self, items):
    
    return SessionContext.session.execute(
        self.insert(values=[
            to_dict(item, self.c)
            for item in items
        ]),
    ).rowcount
658514
def compile_insert(self, query, values):
        
        # Essentially we will force every insert to be treated as a batch insert which
        # simply makes creating the SQL easier for us since we can utilize the same
        # basic routine regardless of an amount of records given to us to insert.
        table = self.wrap_table(query.from__)

        if not isinstance(values, list):
            values = [values]

        columns = self.columnize(values[0].keys())

        # We need to build a list of parameter place-holders of values that are bound
        # to the query. Each insert should have the exact same amount of parameter
        # bindings so we can just go off the first list of values in this array.
        parameters = self.parameterize(values[0].values())

        value = ['(%s)' % parameters] * len(values)

        parameters = ', '.join(value)

        return 'INSERT INTO %s (%s) VALUES %s' % (table, columns, parameters)
164508
def execute(self, using=None):
        
        if not using:
            using = self.getConnection()

        insertedEntities = {}
        for klass in self.orders:
            number = self.quantities[klass]
            if klass not in insertedEntities:
                insertedEntities[klass] = []
            for i in range(0,number):
                    insertedEntities[klass].append( self.entities[klass].execute(using, insertedEntities) )

        return insertedEntities
809984
def insert(self, rows):
        
        if len(rows) == 0:
            return

        sql, sql_args = self.get_insert_sql(rows)

        # get the cursor to execute the query
        cursor = self.get_cursor()

        # execute the query
        cursor.execute(sql, sql_args)
920956
def get_statements(self):
        
        stmt_lists = [v for k, v in self.stmts.items()]
        stmts = []
        for s in stmt_lists:
            stmts += s
        return stmts
979424
function getExecuteInsertSQL($statement) {

         $results = array();  //Array where all the sentences will be stored

         if ($sentences = $statement->getSentences()) {
             foreach ($sentences as $sentence) {
                 // Get the list of fields
                 $fields = $statement->getFieldsFromInsertSentence($sentence);
                 // Get the values of fields
                 $values = $statement->getValuesFromInsertSentence($sentence);
                 // Look if we have some CONCAT value and transform it dynamically
                 foreach($values as $key => $value) {
                     // Trim single quotes
                     $value = trim($value,"'");
                     if (stristr($value, 'CONCAT') !== false){
                         // Look for data between parenthesis
                         preg_match("/CONCAT\s*\((.*)\)$/is", trim($value), $matches);
                         if (isset($matches[1])) {
                             $part = $matches[1];
                             // Convert the comma separated string to an array
                             $arr = xmldb_object::comma2array($part);
                             if ($arr) {
                                 $value = $this->getConcatSQL($arr);
                             }
                         }
                     }
                     // Values to be sent to DB must be properly escaped
                     $value = $this->addslashes($value);
                     // Back trimmed quotes
                     $value = "'" . $value . "'";
                     // Back to the array
                     $values[$key] = $value;
                 }

                 // Iterate over fields, escaping them if necessary
                 foreach($fields as $key => $field) {
                     $fields[$key] = $this->getEncQuoted($field);
                 }
                 // Build the final SQL sentence and add it to the array of results
             $sql = 'INSERT INTO ' . $this->getEncQuoted($this->prefix . $statement->getTable()) .
                         '(' . implode(', ', $fields) . ') ' .
                         'VALUES (' . implode(', ', $values) . ')';
                 $results[] = $sql;
             }

         }
         return $results;
    }
1089766
def insert_statement(table, columns, values):
    """"""
    if not all(isinstance(r, (list, set, tuple)) for r in values):
        values = [[r] for r in values]
    rows = []
    for row in values:
        new_row = []
        for col in row:
            if col is None:
                new_col = 'NULL'
            elif isinstance(col, (int, float, Decimal)):
                new_col = str(MySQLConverterBase().to_mysql(col))
            else:
                string = str(MySQLConverterBase().to_mysql(col))
                if "'" in string:
                    new_col = '"' + string + '"'
                else:
                    new_col = "'" + string + "'"
            new_row.append(new_col)
        rows.append(', '.join(new_row))
    vals = '(' + '),\n\t('.join(rows) + ')'
    statement = "INSERT INTO\n\t{0} ({1}) \nVALUES\n\t{2}".format(wrap(table), cols_str(columns), vals)
    return statement
1353063
def insert(self, fields, values):
        '''
        
        '''
        if fields:
            _fields = ' (%s) ' % ','.join(fields)
        else:
            _fields = ''
        _values = ','.join('?' * len(values))
        query = '''
        INSERT INTO %s %s VALUES (%s)
        ''' % (self._name, _fields, _values)
        self._cursor.execute(query, tuple(values))
        self._connection.commit()
        return self._cursor.lastrowid