代码之家  ›  专栏  ›  技术社区  ›  Matt

将结果集从SQL数组转换为字符串数组

  •  44
  • Matt  · 技术社区  · 13 年前

    我正在查询 information_schema.columns 表。结果集使用表名查找所有列名、类型以及它是否可以为null(主键“id”除外)。这是正在使用的查询:

    SELECT column_name, is_nullable,data_type FROM information_schema.columns
    WHERE lower(table_name) = lower('TABLE1') AND column_name != 'id'
    ORDER BY ordinal_position;
    

    我为这些结果中的每一个都有一个字符串数组,并且我正在尝试使用ResultSet方法 getArray(String columnLabel) 以避免在结果中循环。我想将返回的数组存储在字符串数组中,但出现类型不匹配错误

    Type mismatch: cannot convert from Array to String[]
    

    有没有办法将SQL数组对象转换或类型转换为String[]?

    相关代码:

    String[] columnName, type, nullable;
    
    //Get Field Names, Type, & Nullability 
    String query = "SELECT column_name, is_nullable,data_type FROM information_schema.columns "
            + "WHERE lower(table_name) = lower('"+tableName+"') AND column_name != 'id' "
            + "ORDER BY ordinal_position";
    
    try{
        ResultSet rs = Query.executeQueryWithRS(c, query);
        columnName = rs.getArray(rs.getArray("column_name"));
        type = rs.getArray("data_type");
        nullable = rs.getArray("is_nullable");
    }catch (Exception e) {
        e.printStackTrace();
    }
    
    4 回复  |  直到 13 年前
        1
  •  63
  •   Community Mohan Dere    6 年前

    使用:

    Array a = rs.getArray("is_nullable");
    String[] nullable = (String[])a.getArray();
    

    如前所述 here

    Array 是SQL类型, getArray() 返回一个要强制转换为java数组的对象。

        2
  •  4
  •   TheWhiteRabbit    13 年前

    将数组泛化为对象

        Object[] type; //this is generic can use String[] directly
        Array rsArray;
    
        rsArray = rs.getArray("data_type");
        type = (Object [])rsArray.getArray();
    

    将其循环用作字符串:

    type[i].toString();
    
        3
  •  3
  •   yglodt    9 年前

    如何从SQL数组中设置ArrayList属性:

    Array a = rs.getArray("col"); // smallint[] column
    if (a != null) {
        yourObject.setListProperty(Arrays.asList((Integer[]) a.getArray()));
    }
    
        4
  •  1
  •   Rajeev Ranjan    7 年前

    这可能很有帮助

    Object[] balance = (Object[]) ((Array) attributes[29]).getArray();
            for (Object bal : balance) {
    
                Object [] balObj =(Object[]) ((Array) bal).getArray();
                for(Object obj : balObj){
                    Struct s= (Struct)obj;
                    if(s != null ){
                        String [] str = (String[]) s.getAttributes();
                        System.out.println(str);
                    }
    
                }
    
            }