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

问题描述 投票:0回答:5

我正在查询 PostgreSQL 数据库中的

information_schema.columns
表。使用表名,结果集查找所有列名、类型以及是否可为空(主键“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();
}
java arrays postgresql jdbc resultset
5个回答
67
投票

用途:

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

此处解释

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


4
投票

将数组泛化为对象

    Object[] type; //this is generic can use String[] directly
    Array rsArray;

    rsArray = rs.getArray("data_type");
    type = (Object [])rsArray.getArray();

将其循环用作字符串:

type[i].toString();

3
投票

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

Array a = rs.getArray("col"); // smallint[] column
if (a != null) {
    yourObject.setListProperty(Arrays.asList((Integer[]) a.getArray()));
}

1
投票

这可能会有帮助

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);
                }

            }

        }

0
投票

在 Kotlin 中,

(resultSet.getArray(resultName)!!.array as Array<*>).toList()
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.