将结果集从SQL数组转换为字符串数组
我正在查询PostgreSQL数据库中的information_schema.columns
表。使用表名称,结果集会查找所有列名称,类型以及是否为空(除了主键'id')。这是正在使用的查询:将结果集从SQL数组转换为字符串数组
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 Array对象转换或强制转换为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();
}
用途:
Array a = rs.getArray("is_nullable");
String[] nullable = (String[])a.getArray();
如所解释的here
Array
是SQL类型,getArray()
返回一个对象投射到Java数组。
概括阵列到对象
Object[] type; //this is generic can use String[] directly
Array rsArray;
rsArray = rs.getArray("data_type");
type = (Object [])rsArray.getArray();
使用它环路字符串:
type[i].toString();
这仍然会导致错误。 “_Type不匹配:无法从数组转换为对象[] _”。我认为主要的问题是ResultSet'getArray'方法返回[java.sql数组](http://docs.oracle.com/javase/7/docs/api/java/sql/Array.html),而不是java.lang Object类下的java.util.Arrays类型。 这是关于我的方法的[javadoc](http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#getArray(java.lang.String))使用。 – Matt 2013-02-18 11:30:47
@Matt编辑和验证,getArray()将返回Array,Array.getArray()返回java数组。 – TheWhiteRabbit 2013-02-18 11:40:40
正确,现在可以工作,但它需要不必要地使用'toString()'。在ResultSet中包含未知或各种对象的情况下,推广到Object []可能会更有用。在我的情况下,我只需要字符串。 – Matt 2013-02-18 11:45:27
谢谢,我尝试过使用'rs.getArray(“is_nullable”)。getArray()',但我认为我没有对它进行类型转换。这似乎解决了我的问题。 – Matt 2013-02-18 11:36:49