PDA

View Full Version : [JAVA] HSQLDB, lista nomi delle colonne


kevinpirola
26-08-2012, 01:50
Ciao a tutti, sto lavorando su un database, per vari motivi avrei però bisogno di ricavare, dato il nome di una tabella, i nomi delle sue colonne.

A tal proposito ho creato due metodi diversi, entrambi che hanno più o meno lo stesso problema, e non so come uscirne.

vi posto quello che ho scritto, per vedere se qualcuno ha l'illuminazione...


public void listTableColumns(String table) throws SQLException {
String[] s = null;
ResultSet rs =
this.connection.prepareStatement("select column_name from information_schema.columns where table_name = '"+
table +"' order by ordinal_position;").executeQuery();
while (!rs.isLast()){
rs.next();
// s[i] = rs.getString(i);
System.out.println(rs.getString("column_name"));
}
}


nello specifico l'errore generato è:


Exception in thread "main" java.sql.SQLException: invalid cursor state: identifier cursor not positioned on row in UPDATE, DELETE, SET, or GET statement: ; ResultSet is empty
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCResultSet.getCurrent(Unknown Source)
at org.hsqldb.jdbc.JDBCResultSet.getColumnInType(Unknown Source)
at org.hsqldb.jdbc.JDBCResultSet.getString(Unknown Source)
at org.hsqldb.jdbc.JDBCResultSet.getString(Unknown Source)
at it.kApps.core.Database.listTableColumns(Database.java:185)
at it.kApps.core.Database.main(Database.java:337)

in cui la riga 185 è quella del "System.out"

qualcuno mi dà una dritta?

newuser
26-08-2012, 12:02
Exception in thread "main" java.sql.SQLException: invalid cursor state: identifier cursor not positioned on row in UPDATE, DELETE, SET, or GET statement: ; ResultSet is empty


Il ResultSet è vuoto, l'errore è nell'interrogazione inviata al DBMS.

banryu79
27-08-2012, 10:20
Prova usando l'interfaccia java.sql.ResultSetMetaData, la ricavi dal ResultSet della query (esegui una query "normale" però):

ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM mytable");
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
String aName = rsmd.getColumnName(1);
String bName = rsmd.getColumnName(2);
String cName = rsmd.getColumnName(3);

kevinpirola
27-08-2012, 18:28
alla fine sono riuscito a risolvere con questo codice:


public ArrayList<String> listTableColumns(String table) throws SQLException {
ArrayList<String> columnNames = new ArrayList<String>();
ResultSet rsColumns = this.connection.prepareStatement(
"SELECT COLUMN_NAME, TYPE_NAME, COLUMN_SIZE FROM INFORMATION_SCHEMA.SYSTEM_COLUMNS WHERE TABLE_NAME = '" + table.toUpperCase()
+ "' AND COLUMN_NAME NOT LIKE 'ID' ORDER BY ORDINAL_POSITION").executeQuery();
while (rsColumns.next()) {
columnNames.add(rsColumns.getString("COLUMN_NAME"));
}
return columnNames;
}


cosa ne pensate? è una rielaborazione di un tot di cose trovate in rete...