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

2022-09-01 05:09:15

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

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

答案 1

用:

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

如此所述

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


答案 2

将数组泛化为对象

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

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

将其循环用作字符串:

type[i].toString();