根据某个字段名条件查询数据列表，返回所有字段

@param conn 数据库连接对象
@param tableName 表名
@param field 字段名
@param values 字段值列表
@return 数据对象列表
@throws SQLException SQL执行异常
423092
public List<Entity> findIn(Connection conn, String tableName, String field, Object... values) throws SQLException{
		return findAll(conn, Entity.create(tableName).set(field, values));
	}
388318
void createTables() throws SQLException {
    try (PreparedStatement prepSt = conn.prepareStatement("CREATE TABLE pings (" +
            "  language_code VARCHAR(5) NOT NULL," +
            "  check_date TIMESTAMP NOT NULL" +
            ")")) {
      prepSt.executeUpdate();
    }
    try (PreparedStatement prepSt = conn.prepareStatement("CREATE TABLE feed_checks (" +
            "  language_code VARCHAR(5) NOT NULL," +
            "  check_date TIMESTAMP NOT NULL" +
            ")")) {
      prepSt.executeUpdate();
    }
    try (PreparedStatement prepSt = conn.prepareStatement("CREATE TABLE feed_matches (" +
            "  id INT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)," +
            "  language_code VARCHAR(5) NOT NULL," +
            "  title VARCHAR(255) NOT NULL," +
            "  rule_id VARCHAR(255) NOT NULL," +
            "  rule_sub_id VARCHAR(255)," +
            "  rule_description VARCHAR(255) NOT NULL," +
            "  rule_message VARCHAR(255) NOT NULL," +
            "  rule_category VARCHAR(255) NOT NULL," +
            "  error_context VARCHAR(500) NOT NULL," +
            "  edit_date TIMESTAMP NOT NULL," +
            "  diff_id INT NOT NULL," +
            "  fix_date TIMESTAMP," +
            "  fix_diff_id INT" +
            ")")) {
      prepSt.executeUpdate();
    }
  }
539823
public static boolean updateRow(Connection conn,
                                    String table,
                                    String[] columns,
                                    String[] values,
                                    String uniqueColumn,
                                    boolean[] numeric) throws SQLException {
        return instance.i_updateRow(conn,
                                    table,
                                    columns,
                                    values,
                                    uniqueColumn,
                                    numeric);
    }
564415
public static Object convertBlob(Connection conn, byte[] value) throws SQLException {
        Object result = createBlob(conn);

        result = convertBlob(result, value);

        return result;
    }
641104
def doSQLInsert(sqlString)
   
      sql = sqlString.dup
      dbname = ""
      state = nil
      fieldName = ""
      fieldValue = ""
      fieldNames = []
      fieldValues = []
      index = 0
      
      clearFieldValuePairList
      
      sql.gsub!("("," ")
      sql.gsub!(")"," ")

      sql.split(' ').each{ |token|
         case token
            when "INSERT", "INTO" 
               state = "getTable"
               next
            when "VALUES" 
               state = "getFieldValue"
               next
         end
         if state == "getTable"
            dbname = token.strip
            state =   "getFieldName"
         elsif state  == "getFieldName" 
            fieldName = token.dup
            fieldName.gsub!("],","")
            fieldName.gsub!('[','')
            fieldName.gsub!(']','')
            fieldName.gsub!(',','')
            fieldNames << fieldName
         elsif state  == "getFieldValue" 
            test = token.dup
            if test[-1,1] == "'" or test[-2,2] == "',"
               fieldValue << token.dup
               if fieldValue[-2,2] == "',"
                  fieldValue.gsub!("',",'')
               end
               fieldValue.gsub!('\'','')
               if fieldValue.length > 0 and fieldNames[index] 
                  addFieldValuePair(fieldNames[index],nil,nil,fieldValue)
                  fieldName = ""
                  fieldValue = ""
               end
               index += 1
            elsif token == ","
               addFieldValuePair(fieldNames[index],nil,nil,"")
               fieldName = ""
               fieldValue = ""
               index += 1
            else
               fieldValue << "#{token.dup} "
            end
         end
      }
      
      if dbname and @dbid.nil?
         dbid = findDBByname( dbname )
      else
         dbid = lookupChdbid( dbname )
      end
      dbid ||= @dbid

      recordid = nil
      if dbid
         recordid,updateid = addRecord(dbid,@fvlist)
      end   
      recordid
      
   end
158253
@SuppressWarnings("resource")
    private CmsSqlConsoleResults executeQuery(String sentence, String poolName) throws SQLException {

        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet res = null;

        CmsSqlManager sqlManager = m_sqlManager;

        try {
            conn = sqlManager.getConnection(poolName);
            stmt = sqlManager.getPreparedStatementForSql(conn, sentence);
            res = stmt.executeQuery();

            // add headings
            ResultSetMetaData metadata = res.getMetaData();
            List<String> heading = new ArrayList<>();
            for (int i = 0; i < metadata.getColumnCount(); i++) {
                heading.add(metadata.getColumnName(i + 1));
            }
            List<List<Object>> data = new ArrayList<List<Object>>();

            // add contents
            while (res.next()) {
                List<Object> row = new ArrayList<Object>();
                for (int i = 0; i < metadata.getColumnCount(); i++) {
                    Object value = res.getObject(i + 1);
                    if ((value instanceof String)
                        || (value instanceof Integer)
                        || (value instanceof Long)
                        || (value instanceof Float)
                        || (value instanceof Double)) {
                        row.add(value);
                    } else if (value == null) {
                        row.add(null);
                    } else {
                        row.add(String.valueOf(value));
                    }
                }
                data.add(row);
            }
            return new CmsSqlConsoleResults(heading, data);
        } finally {
            sqlManager.closeAll(null, conn, stmt, res);
        }
    }
94858
public int count(Connection conn, Entity where) throws SQLException {
		checkConn(conn);
		
		final Query query = new Query(SqlUtil.buildConditions(where), where.getTableName());
		PreparedStatement ps = null;
		try {
			ps = dialect.psForCount(conn, query);
			return SqlExecutor.query(ps, new NumberHandler()).intValue();
		} catch (SQLException e) {
			throw e;
		} finally {
			DbUtil.close(ps);
		}
	}
1049659
private void createTables(Connection conn) throws DatabaseException {
        LOGGER.debug("Creating database structure");

        try (InputStream is = FileUtils.getResourceAsStream(DB_STRUCTURE_RESOURCE)) {
            final String dbStructure = IOUtils.toString(is, StandardCharsets.UTF_8);

            Statement statement = null;
            try {
                statement = conn.createStatement();
                statement.execute(dbStructure);
            } catch (SQLException ex) {
                LOGGER.debug("", ex);
                throw new DatabaseException("Unable to create database statement", ex);
            } finally {
                DBUtils.closeStatement(statement);
            }
        } catch (IOException ex) {
            throw new DatabaseException("Unable to create database schema", ex);
        }
    }
187012
private static String parseFieldsSql(String tableName, Supplier<ConditionEnum>[] conditions) {
        final String[] sql = {"SELECT * FROM " + tableName};
        if (null == conditions) {
            return sql[0];
        }
        Stream.of(conditions)
                .filter(conditionEnumSupplier -> conditionEnumSupplier.get().equals(ConditionEnum.FIELDS))
                .findFirst()
                .ifPresent(conditionEnumSupplier -> {
                    Fields      fields    = (Fields) conditionEnumSupplier;
                    Set<String> fieldsSet = fields.getFields();
                    sql[0] = "SELECT " + fieldsSet.stream().collect(Collectors.joining(",")) + " FROM " + tableName;
                });
        return sql[0];
    }
252708
public Long execute(final ConnectionResource _con)
        throws SQLException
    {
        final boolean supGenKey = Context.getDbType().supportsGetGeneratedKeys();

        Long ret = null;
        if (this.newId && !supGenKey)  {
            ret = Context.getDbType().getNewId(_con, getTableName(), getIdColumn());
            this.column(getIdColumn(), ret);
        }

        final StringBuilder cmd = new StringBuilder()
            .append(Context.getDbType().getSQLPart(SQLPart.INSERT))
            .append(" ")
            .append(Context.getDbType().getSQLPart(SQLPart.INTO))
            .append(" ")
            .append(Context.getDbType().getTableQuote())
            .append(getTableName())
            .append(Context.getDbType().getTableQuote())
            .append(" ")
            .append(Context.getDbType().getSQLPart(SQLPart.PARENTHESIS_OPEN));

        final StringBuilder val = new StringBuilder();

        // append SQL values
        boolean first = true;
        for (final ColumnWithSQLValue col : getColumnWithSQLValues())  {
            if (first)  {
                first = false;
            } else  {
                cmd.append(Context.getDbType().getSQLPart(SQLPart.COMMA));
                val.append(Context.getDbType().getSQLPart(SQLPart.COMMA));
            }
            cmd.append(Context.getDbType().getColumnQuote())
                .append(col.getColumnName())
                .append(Context.getDbType().getColumnQuote());
            val.append(col.getSqlValue());
        }

        // append values
        for (final AbstractColumnWithValue<?> col : getColumnWithValues())  {
            if (first)  {
                first = false;
            } else  {
                cmd.append(Context.getDbType().getSQLPart(SQLPart.COMMA));
                val.append(Context.getDbType().getSQLPart(SQLPart.COMMA));
            }
            cmd.append(Context.getDbType().getColumnQuote())
                .append(col.getColumnName())
                .append(Context.getDbType().getColumnQuote());
            val.append('?');
        }
        cmd.append(Context.getDbType().getSQLPart(SQLPart.PARENTHESIS_CLOSE))
            .append(Context.getDbType().getSQLPart(SQLPart.VALUES))
            .append(Context.getDbType().getSQLPart(SQLPart.PARENTHESIS_OPEN))
            .append(val)
            .append(Context.getDbType().getSQLPart(SQLPart.PARENTHESIS_CLOSE));

        SQLInsert.LOG.debug("Executing SQL: {}", cmd.toString());

        final PreparedStatement stmt;
        if (this.newId && supGenKey) {
            if (Context.getDbType().supportsMultiGeneratedKeys()) {
                stmt = _con.prepareStatement(cmd.toString(), new String[]{ getIdColumn() });
            } else {
                stmt = _con.prepareStatement(cmd.toString(), Statement.RETURN_GENERATED_KEYS);
            }
        } else {
            stmt = _con.prepareStatement(cmd.toString());
        }

        int index = 1;
        for (final AbstractColumnWithValue<?> col : getColumnWithValues())  {
            if (SQLInsert.LOG.isDebugEnabled()) {
                SQLInsert.LOG.debug("    " + index + " = " + col.getValue());
            }
            col.set(index++, stmt);
        }

        try {
            final int rows = stmt.executeUpdate();
            if (rows == 0) {
                throw new SQLException("Object for SQL table '" + getTableName()
                        + "' does not exists and was not inserted.");
            }

            // if auto generated get new id
            if (this.newId && supGenKey) {
                final ResultSet resultset = stmt.getGeneratedKeys();
                if (resultset.next()) {
                    ret = resultset.getLong(1);
                }
                resultset.close();
            }
        } finally  {
            stmt.close();
        }

        if (this.newId && SQLInsert.LOG.isDebugEnabled()) {
            SQLInsert.LOG.debug("new generated id " + ret);
        }

        return ret;
    }
21944
public static PreparedStatement prepareStatement(Connection conn, SqlBuilder sqlBuilder) throws SQLException {
		return prepareStatement(conn, sqlBuilder.build(), sqlBuilder.getParamValueArray());
	}
1093688
protected final void doInsert(Connection c) throws SQLException {
		PreparedStatement stmt = null;
		try {
			stmt = c.prepareStatement("insert into foo values (?, ?)  ");
			stmt.setInt(1, rand.nextInt(99999));
			stmt.setString(2, "This is a text");
			stmt.executeUpdate();
		} finally {
			if (stmt != null) {
				stmt.close();
			}
		}
	}
410563
public static PreparedStatement prepareStatement(Connection conn, String sql, Object... params) throws SQLException {
		Assert.notBlank(sql, "Sql String must be not blank!");

		sql = sql.trim();
		SqlLog.INSTASNCE.log(sql, params);
		PreparedStatement ps;
		if (StrUtil.startWithIgnoreCase(sql, "insert")) {
			// 插入默认返回主键
			ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
		} else {
			ps = conn.prepareStatement(sql);
		}
		return fillParams(ps, params);
	}
791340
public PageResult<Entity> page(Connection conn, Collection<String> fields, Entity where, Page page) throws SQLException {
		checkConn(conn);
		
		//查询全部
		if(null == page){
			List<Entity> entityList = this.find(conn, fields, where, new EntityListHandler());
			final PageResult<Entity> pageResult = new PageResult<Entity>(0, entityList.size(), entityList.size());
			pageResult.addAll(entityList);
			return pageResult;
		}
		
		final int count = count(conn, where);
		PageResultHandler pageResultHandler = PageResultHandler.create(new PageResult<Entity>(page.getPageNumber(), page.getPageSize(), count));
		return this.page(conn, fields, where, page, pageResultHandler);
	}
308995
public void setFields(List<Field> fields) throws SqlParseException {
		/*
		zhongshu-comment select * from tbl_a;
		select * 这种sql语句的select.getFields().size()为0
		 */
		if (select.getFields().size() > 0) {
			ArrayList<String> includeFields = new ArrayList<String>();
			ArrayList<String> excludeFields = new ArrayList<String>();

			for (Field field : fields) {
				if (field instanceof MethodField) { //zhongshu-comment MethodField是Field的子类，而且Field也就只有MethodField这一个子类了
					MethodField method = (MethodField) field;
					if (method.getName().toLowerCase().equals("script")) {
						/*
						zhongshu-comment scripted_field only allows script(name,script) or script(name,lang,script)
						script类型的MethodField是不会加到include和exclude中的
						 */
						handleScriptField(method);
					} else if (method.getName().equalsIgnoreCase("include")) {
					    String f;
						for (KVValue kvValue : method.getParams()) {
							//zhongshu-comment select a,b,c 中的a、b、c字段add到includeFields中
                            f = kvValue.value.toString();
                            fieldNames.add(f);
                            includeFields.add(f);
						}
					} else if (method.getName().equalsIgnoreCase("exclude")) {
						for (KVValue kvValue : method.getParams()) {
							excludeFields.add(kvValue.value.toString()) ;
						}
					}
				} else if (field != null) {
                    fieldNames.add(field.getName());
					includeFields.add(field.getName());
				}
			}

			request.setFetchSource(
					includeFields.toArray(new String[includeFields.size()]),
					excludeFields.toArray(new String[excludeFields.size()])
			);
		}
	}
768942
public void createGenerator (Connection conn, String tableName, String columnName, int initValue)
        throws SQLException
    {
        if (initValue == 1) {
            return; // that's the default! yay, do nothing
        }

        String seqname = "\"" + tableName + "_" + columnName + "_seq\"";
        Statement stmt = conn.createStatement();
        try {
            stmt.executeQuery("select setval('" + seqname + "', " + initValue + ", false)");
        } finally {
            JDBCUtil.close(stmt);
        }
        log("Initial value of " + seqname  + " set to " + initValue + ".");
    }
60437
public synchronized int delete (Connection conn, T[] objects)
        throws SQLException
    {
        if (primaryKeys == null) {
            throw new IllegalStateException(
                "No primary key for table " + name + ".");
        }
        int nDeleted = 0;
        StringBuilder sql = new StringBuilder(
            "delete from " + name + " where " + primaryKeys[0] + " = ?");
        for (int i = 1; i < primaryKeys.length; i++) {
            sql.append(" and ").append(primaryKeys[i]).append(" = ?");
        }
        PreparedStatement deleteStmt = conn.prepareStatement(sql.toString());
        for (int i = 0; i < objects.length; i++) {
            for (int j = 0; j < primaryKeys.length; j++) {
                fields[primaryKeyIndices[j]].bindVariable(
                    deleteStmt, objects[i], j+1);
            }
            deleteStmt.addBatch();
        }
        int rc[] = deleteStmt.executeBatch();
        for (int k = 0; k < rc.length; k++) {
            nDeleted += rc[k];
        }
        deleteStmt.close();
        return nDeleted;
    }