H2 DatabaseとSchemaCrawlerでテーブルのカラムを列挙する関数を作成するには、以下のスクリプトを実行します。
create alias if not exists sc_get_columns as $$
import java.io.*;
import java.util.*;
import java.sql.*;
import org.h2.tools.*;
import java.net.*;
import schemacrawler.schema.*;
import schemacrawler.schemacrawler.*;
import schemacrawler.utility.*;
@CODE
ResultSet sc_get_columns(String jdbcDriver, String url,
String user, String password, String schemaName,
String tableName)
throws Exception
{
if( jdbcDriver == null ){
throw new Exception("jdbcDriver is not specified.");
}
if( url == null ){
throw new Exception("url is not specified.");
}
if( user == null ){
throw new Exception("user is not specified.");
}
if( password == null ){
throw new Exception("password is not specified.");
}
if( schemaName == null ){
throw new Exception("schemaName is not specified.");
}
if( tableName == null ){
throw new Exception("tableName is not specified.");
}
Class.forName(jdbcDriver);
Connection conn = null;
SimpleResultSet rs = new SimpleResultSet();
rs.addColumn("POS", Types.NUMERIC, 4, 0);
rs.addColumn("NAME", Types.VARCHAR, 4096, 0);
rs.addColumn("TYPENAME", Types.VARCHAR, 4096, 0);
rs.addColumn("DECIMAL_DIGITS", Types.NUMERIC, 4, 0);
rs.addColumn("SIZE", Types.NUMERIC, 10, 0);
rs.addColumn("WIDTH", Types.VARCHAR, 4096, 0);
rs.addColumn("NULLABLE", Types.BOOLEAN, 1, 0);
try
{
conn = DriverManager.getConnection(url, user, password);
SchemaCrawlerOptions options = new SchemaCrawlerOptions();
options.setSchemaInfoLevel(SchemaInfoLevel.maximum());
Database db = SchemaCrawlerUtility.getDatabase(conn, options);
Schema schema = db.getSchema(schemaName);
if( schema != null ){
Table table = schema.getTable(tableName);
if( table != null ){
Column columns[] = table.getColumns();
for(int li=0;li<columns.length;li++){
rs.addRow(columns[li].getOrdinalPosition(),
columns[li].getName(),
columns[li].getType().getTypeName(),
columns[li].getDecimalDigits(),
columns[li].getSize(),
columns[li].getWidth(),
columns[li].isNullable());
}
}
}
}
finally
{
if( conn != null )conn.close();
}
return rs;
}
$$
実行例
select * from
sc_get_columns('org.postgresql.Driver',
'jdbc:postgresql://localhost:5432/postgres',
'postgres', 'postgres', 'public', 'test1');
※以下のjarをCLASSPATH環境変数に追加
schemacrawler-8.5.1.jar, schemacrawler-postgresql-8.5.1.jar
○動作環境
JDK6 Update23, H2 Database 1.2.149 (2011-01-07), SchemaCrawler 8.5.1
○関連情報
・SchemaCrawlerのウェブサイト
http://schemacrawler.sourceforge.net/
・H2 Databaseに関する他の記事は
こちらを参照してください。