构造一个插入SQL

@param activeRecord ActiveRecord对象
@return 返回insert sql语句
355026
static QueryMeta buildInsertSql(ActiveRecord activeRecord) {
        QueryMeta     queryMeta = new QueryMeta();
        String        tableName = activeRecord.getTableName();
        StringBuilder sb        = new StringBuilder(Const.SQL_INSERT + " ");
        sb.append(tableName);
        sb.append(" (");

        StringBuffer values = new StringBuffer(" VALUES (");
        Stream.of(activeRecord.getClass().getDeclaredFields())
                .filter(field -> null == field.getAnnotation(Transient.class))
                .forEach(field -> {
                    try {
                        field.setAccessible(true);
                        if (field.get(activeRecord) != null) {
                            Pair<String, String> pair = getColumnName(field);
                            sb.append(pair.getLeft()).append(", ");
                            values.append(':').append(pair.getRight()).append(", ");
                        }
                    } catch (Exception e) {
                    }
                });

        sb.append(')');
        values.append(')');

        String sql = sb.append(values).toString().replace(", )", ")");
        queryMeta.setSql(sql);
        return queryMeta;
    }
351932
def insert_many(self, *args, **kwargs):
        
        # print(f"database.collection: '{self.database.name}.{self.collection.name}'")
        result = self.collection.insert_many(*args, **kwargs)
        return result.inserted_ids
831530
function (sql) {
            if (this._joinedDataset) {
                return format(" %s FROM %s%s", this._sourceList(this.__opts.from[0]), this._sourceList(this.__opts.from), this._selectJoinSql());
            } else {
                return this._super(arguments);
            }
        }
485453
public function useActiveRecord($activeRecord, $attribute)
    {
        $this->filename = $this->getFilenameFor($activeRecord, $attribute);

        return $this;
    }
402593
protected function insertRecord()
    {
        $sql = 'INSERT INTO '.$this->fq_name;
        $cols = '(';
        $vals = '(';
        $args = array();
        $table_def = $this->getDefinition();
        foreach($this->instance as $column => $value) {
            if (isset($this->columns[$column]['increment']) && $this->columns[$column]['increment']) {
                // omit autoincrement column from insert
                continue;
            } else if (!isset($table_def[$column])) {
                // underlying table is missing this column
                continue;
            }
            $cols .= $this->connection->identifierEscape($column).',';
            $vals .= '?,';    
            $args[] = $value;
        }
        $cols = substr($cols,0,strlen($cols)-1).')';
        $vals = substr($vals,0,strlen($vals)-1).')';
        $sql .= ' '.$cols.' VALUES '.$vals;

        $prep = $this->connection->prepare($sql);
        $result = $this->connection->execute($prep, $args);

        if ($result) {
            $this->record_changed = false;

            /** if the insert succeeded and the table contains an incrementing
                id column, that value will most likely be more useful
                than the result object */
            foreach($this->columns as $name => $info) {
                if (isset($info['increment']) && $info['increment'] === true) {
                    $new_id = $this->connection->insertID();
                    if ($new_id !== false) {
                        $result = $new_id;
                        break;
                    }
                }
            }
        }

        return $result;
    }
190474
def cast_with_active_record(object, type)
      cast = cast_without_active_record(object, type)
      return cast if !defined?(::ActiveRecord::Base)

      if object.is_a?(::ActiveRecord::Base)
        cast = :active_record_instance
      elsif object.is_a?(::ActiveModel::Errors)
        cast = :active_model_error
      elsif object.is_a?(Class) && object.ancestors.include?(::ActiveRecord::Base)
        cast = :active_record_class
      elsif type == :activerecord_relation || object.class.ancestors.include?(::ActiveRecord::Relation)
        cast = :array
      end
      cast
    end
1257073
def _execute(sql, name = nil)
      if ::ActiveRecord::ConnectionAdapters::JdbcConnection::select?(sql)
        @connection.execute_query(sql)
      elsif ::ActiveRecord::ConnectionAdapters::JdbcConnection::insert?(sql)
        insert(sql, name)
      else
        @connection.execute_update(sql)
      end
    end
974848
public static <T> SqlParamsPairs getInsertFromObject(T po) throws Exception{
		
		//用来存放insert语句
		StringBuffer insertSql = new StringBuffer();
		//用来存放?号的语句
		StringBuffer paramsSql = new StringBuffer();
		
		//用来存放参数值
		List<Object> params = new ArrayList<Object>();
		
		//分析表名
		String tableName = getTableName(po.getClass());
		
		insertSql.append("insert into " + tableName + " (");
		
		//计数器
		int count=0;
		
		//分析列
		Field[] fields = po.getClass().getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			Field f = fields[i];
			
			if("serialVersionUID".equals(f.getName())){
				continue;
			}
			
			//获取具体参数值
			Method getter = getGetter(po.getClass(), f);
			
			if(getter == null){
				continue;
			}
			
			Object value = getter.invoke(po);
			if(value == null){
				//如果参数值是null就直接跳过（不允许覆盖为null值，规范要求更新的每个字段都要有值，没有值就是空字符串）
				continue;
			}
			
			Transient tranAnno = getter.getAnnotation(Transient.class);
			if(tranAnno != null){
				//如果有 Transient 标记直接跳过
				continue;
			}
			
			//获取字段名
			String columnName = getColumnNameFromGetter(getter, f);
			
			if(count!=0){
				insertSql.append(",");
			}
			insertSql.append(columnName);
			
			if(count!=0){
				paramsSql.append(",");
			}
			paramsSql.append("?");
			
			params.add(value);
			count++;
		}
		
		insertSql.append(") values (");
		insertSql.append(paramsSql + ")");
		
		SqlParamsPairs sqlAndParams = new SqlParamsPairs(insertSql.toString(), params.toArray());
		logger.debug(sqlAndParams.toString());
		
		return sqlAndParams;
		
	}
6092
def insertSQL(conn, sql, args=None):
    '''
    
    '''
    with doCursor(conn) as cursor:
        cursor.execute(sql, args)
        id = conn.insert_id()
        return id
1040828
def create_sql(self, insert=False, version=False, version_fieldname=None,
                   fields=None, ec=None, compare=False):
        
        version_fieldname = version_fieldname or 'version'
        #fix when d is empty, orm will not insert record bug 2013/04/07
        if not self._key or insert:
            d = self._get_data(fields, compare=compare)
            if d:
                return rawsql(self.table.insert().values(**d),
                              ec or self.get_engine_name()) + ';'

        else:
            d = self._get_data(fields, compare=compare)
            _key = d.pop(self._primary_field)
            if d:
                _cond = self.table.c[self._primary_field] == self._key
                if version:
                    version_field = self.table.c.get(version_fieldname)
                    if version_field is None:
                        raise KindError("version_fieldname %s is not existed in Model %s" % (version_fieldname, self.__class__.__name__))
                    _version_value = getattr(self, version_fieldname, 0)
                    # setattr(self, version_fieldname, _version_value+1)
                    d[version_fieldname] = _version_value+1
                    _cond = (version_field == _version_value) & _cond

                return rawsql(self.table.update(_cond).values(**d),
                              ec or self.get_engine_name()) + ';'
        return ''
1317633
function insert() {
    var insertValues = this.single.insert || [];
    var sql = 'insert into ' + this.tableName + ' ';

    if (Array.isArray(insertValues)) {
      if (insertValues.length === 0) {
        return '';
      }
    } else if (typeof insertValues === 'object' && isEmpty(insertValues)) {
      return sql + this._emptyInsertValue;
    }

    var insertData = this._prepInsert(insertValues);
    this.__insertValues = insertData.values;
    if (typeof insertData === 'string') {
      sql += insertData;
    } else {
      if (insertData.columns.length) {
        sql += '(' + this.formatter.columnize(insertData.columns);
        sql += ') values (';
        sql += this.formatter.parameterize(insertData.columns);
        sql += ')';
      } else if (insertValues.length === 1 && insertValues[0]) {
        sql += this._emptyInsertValue;
      } else {
        sql = '';
      }
    }
    var out = {
      sql: sql,
      bindings: insertData.values
    };
    if (out.sql !== '') {
      out.returning = this.single.returning;
    }
    return out;
  }
547793
def insert_many(objects, using="default"):
    
    if not objects:
        return

    import django.db.models
    from django.db import connections
    from django.db import transaction
    con = connections[using]

    model = objects[0].__class__
    fields = [f for f in model._meta.fields
              if not isinstance(f, django.db.models.AutoField)]
    parameters = []
    for o in objects:
        params = tuple(f.get_db_prep_save(f.pre_save(o, True), connection=con)
                       for f in fields)
        parameters.append(params)

    table = model._meta.db_table
    column_names = ",".join(con.ops.quote_name(f.column) for f in fields)
    placeholders = ",".join(("%s",) * len(fields))
    con.cursor().executemany("insert into %s (%s) values (%s)"
                             % (table, column_names, placeholders), parameters)
    transaction.commit_unless_managed(using=using)
1127610
public int insert(String sql) {
        String msId = msUtils.insert(sql);
        return sqlSession.insert(msId);
    }
1171220
def rdf_insert(uriS, uriP, uriO)
      @rdf.insert RDF::Statement(uriS, uriP, uriO)
    end
769782
def insert(self):
        """"""
        self.default_val = 0
        #fields = self.fields
        #fields = self.orm_class.depart(self.fields, is_update=False)
        #self.set_fields(fields)
        return self.interface.insert(
            self.schema,
            self.fields
        )

        return self.interface.insert(self.schema, self.fields)
651280
def query(sql, options=nil) #:nodoc:
      raise ArgumentError, 'query is blank' if blank? sql

      options_pattern = { :limit => :optional }
      verify_options(options, options_pattern) unless options.nil?

      limit = ''
      limit = "/#{options[:limit]}" if !options.nil? and options.include?(:limit)

      response = call_server(:method => :get, :uri => "query/#{@database}/sql/#{CGI::escape(sql)}#{limit}")
      entries = process_response(response) do
        raise NotFoundError, 'record not found' if response.body =~ /ORecordNotFoundException/
      end

      rslt = entries['result']
      # mixin all document entries (they have '@class' attribute)
      rslt.each { |doc| doc.extend Orientdb4r::DocumentMetadata unless doc['@class'].nil? }
      rslt
    end
120883
def get_sql_insert(table: str,
                   fieldlist: Sequence[str],
                   delims: Tuple[str, str] = ("", "")) -> str:
    """"""
    return (
        "INSERT INTO " + delimit(table, delims) +
        " (" +
        ",".join([delimit(x, delims) for x in fieldlist]) +
        ") VALUES (" +
        ",".join(["?"] * len(fieldlist)) +
        ")"
    )