args: if sql has parameters defined with either %s or %(key)s then args should be a either list or dict of parameter
    values respectively.
    returns the insert id
6092
def insertSQL(conn, sql, args=None):
    '''
    
    '''
    with doCursor(conn) as cursor:
        cursor.execute(sql, args)
        id = conn.insert_id()
        return id
567096
public static String substitute(String sql, Object... params) {
        try {
            if (params == null || params.length == 0)
                return sql;
            String subst = sql;
            int start = 0;
            int q;
            for (int i = 0; start < subst.length() && (q = subst.indexOf('?', start)) >= 0; i++) {
                Object param = params[i];
                String p = String.valueOf(param);
                if (param != null && !(param instanceof Integer) && !(param instanceof Long))
                    p = "'" + p + "'";
                subst = subst.substring(0, q) + p + subst.substring(q + 1);
                start = q + p.length();
            }
            return subst;
        }
        catch (Throwable t) {
            logger.severeException(t.getMessage(), t);
            return sql;
        }
    }
436517
protected PreparedStatement executeSql(String sql,
    MapSqlParameterSource args)
  {
    // XXX: uses raw type, what are the parameters to Map in MapSqlParameterSource?
    Map<String, Object> parameters = args != null ? args.getValues()
      : new HashMap<String, Object>();

    for (Map.Entry<String, Object> placeHolderEntry : parameters.entrySet())
    {
      String key = placeHolderEntry.getKey();
      String value = placeHolderEntry.getValue().toString();
      log.debug("substitution for parameter '" + key + "' in SQL script: "
        + value);
      sql = sql.replaceAll(key, Matcher.quoteReplacement(value));
    }
    
    log.debug("Executing SQL\n{}", sql);
    
    CancelableStatements cancelableStats
      = new CancelableStatements(
        sql, statementController);

    // register the statement, so we could try to interrupt it in the gui.
    if (statementController != null)
    {
      statementController.registerStatement(cancelableStats.statement);
    }
    else
    {
      log.debug("statement controller is not initialized");
    }
    getJdbcTemplate().execute(cancelableStats, cancelableStats);
    return cancelableStats.statement;

  }
1219037
public <T> List<T> querySingleRowTypedResults(String sql, String[] args) {
		return db.querySingleRowTypedResults(sql, args);
	}
715230
function prepareBatchInsertSql(tableName, toInserts, options, needArgs) {
  options = options || {};
  var returnFields = options.fields || [];

  var insertsCount = toInserts.length;
  var oneElem = toInserts[0];
  var sql = 'insert into "' + tableName + '"(';
  var fieldClause = '';
  var valueClause = ' values';
  var args = null;
  if (needArgs) args = [];
  var fieldList = Object.keys(oneElem);
  var fieldNameCount = fieldList.length;
  var elemKeyIndex = 1;
  fieldList.forEach(function (f) {
    let endSymbol = ',';
    if (fieldNameCount == elemKeyIndex) endSymbol = ')';
    fieldClause += '"' + f + '"' + endSymbol;
    elemKeyIndex++;
  });

  for (var i = 0; i < insertsCount; i++) {
    var toInsert = toInserts[i];
    var keyCount = Object.keys(toInsert).length;
    if (keyCount != fieldNameCount) throw new Error('prepareBatchInsertSql:one element\'s key count:' + keyCount + ' not equal first element:' + fieldNameCount);
    var keyIndex = 1;
    fieldList.forEach(function (f) {
      let endSymbol = ',';
      if (keyIndex == 1) valueClause += '(';
      if (keyIndex == keyCount) endSymbol = ')';
      var val = toInsert[f];
      var valType = typeof val;
      if (valType == 'string' || valType == 'object') {
        if (valType == 'object') val = JSON.stringify(val);
        valueClause += '$' + (args.length + 1) + endSymbol;
        args.push(val);
      } else if (valType == 'number' || valType == 'boolean') {
        valueClause += val + endSymbol;
      } else {
        console.error('tableName:', tableName, " toInserts:", JSON.stringify(toInserts), " f:", f, " valType:", valType);
        throw new Error('prepareBatchInsertSql:filed:' + f + ',invalid value type, must be one of them:string,number');
      }
      keyIndex++;
    });

    if (i < (insertsCount - 1)) {
      valueClause += ',';
    }
  }
  sql = sql + fieldClause + valueClause;
  if (returnFields) sql += fieldsToReturningClause(returnFields);
  return { sql: sql, args: needArgs ? args : [] };
}
624638
public static String sqlinsert(List<?> parsedArgs) throws SQLException {
    if (parsedArgs.size() != 4) {
      throw new PSQLException(GT.tr("{0} function takes four and only four argument.", "insert"),
          PSQLState.SYNTAX_ERROR);
    }
    StringBuilder buf = new StringBuilder();
    buf.append("overlay(");
    buf.append(parsedArgs.get(0)).append(" placing ").append(parsedArgs.get(3));
    buf.append(" from ").append(parsedArgs.get(1)).append(" for ").append(parsedArgs.get(2));
    return buf.append(')').toString();
  }
518389
def insert(self, table, values):
        
        assert isinstance(values, dict)

        sb = self.sql_builder().insert(table)
        for column, value in values.iteritems():
            values[column] = sb.create_positional_parameter(value)
        return sb.values(values).execute()
1263089
public <E extends Object> int executeSQL(String sql, List<E> params) {
        if (params == null || params.size() == 0) {
            return jdbcTemplate.update(sql);
        } else {
            return jdbcTemplate.update(sql, params.toArray(new Object[params.size()]));
        }
    }
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)
630655
def _construct_inserts(self, record, new_columns, rename_columns, retype_columns, resize_columns):

        '''  '''

        insert_kwargs = {}

        for key, value in new_columns.items():

        # retrieve value for key (or from old key name)
            if key in rename_columns.keys():
                record_value = getattr(record, rename_columns[key], None)
            else:
                record_value = getattr(record, key, None)

        # attempt to convert datatype
            if record_value:
                if key in retype_columns.keys():
                    try:
                        old_list = False
                        if isinstance(record_value, bytes):
                            record_value = pickle.loads(record_value)
                            old_list = True
                        if retype_columns[key] == 'boolean':
                            record_value = bool(record_value)
                        elif retype_columns[key] == 'string':
                            if old_list:
                                record_value = ','.join(record_value)
                            else:
                                record_value = str(record_value)
                        elif retype_columns[key] == 'integer':
                            if old_list:
                                record_value = int(record_value[0])
                            else:
                                record_value = int(record_value)
                        elif retype_columns[key] == 'float':
                            if old_list:
                                record_value = int(record_value[0])
                            else:
                                record_value = float(record_value)
                        elif retype_columns[key] == 'list':
                            if isinstance(record_value, str):
                                record_value = pickle.dumps(record_value.split(','))
                            else:
                                record_value = pickle.dumps([record_value])
                    except:
                        record_value = None
        
        # attempt to resize string data 
                if key in resize_columns.keys():
                    max_length = resize_columns[key]
                    try:
                        if len(record_value) > max_length:
                            record_value = record_value[0:max_length]
                    except:
                        record_value = None

                insert_kwargs[key] = record_value

        return insert_kwargs
11028
public void bindArgument(@NotNull PreparedStatement ps, int index, @Nullable Object value) throws SQLException {
        ArgumentBinder.bindArgument(ps, index, value);
    }
331045
def arg_to_soql(arg):
    
    conversion = sql_conversions.get(type(arg))
    if conversion:
        return conversion(arg)
    for type_ in subclass_conversions:
        if isinstance(arg, type_):
            return sql_conversions[type_](arg)
    return sql_conversions[str](arg)
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)) +
        ")"
    )
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
881277
def str_args(args):
    
    res = []
    for x in args:
        if isinstance(x, tuple) and len(x) == 2:
            key, value = x
            if value and str_arg(value):
                res += ["%s=%s" % (key, str_arg(value))]
        else:
            res += [str_arg(x)]
    return ', '.join(res)
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
979095
def insert_parameter(self, pname, ptype):
        ""
        index = self.insert_id(pname, SharedData.KINDS.PARAMETER, SharedData.KINDS.PARAMETER, ptype)
        #set parameter's attribute to it's ordinal number
        self.table[index].set_attribute("Index", self.shared.function_params)
        #set parameter's type in param_types list of a function
        self.table[self.shared.function_index].param_types.append(ptype)
        return index