DataBaseMetaDataデータベースからの読み込みデータベースのプロパティについて
2162 ワード
package test;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import common.DbUtils;
public class DatabaseInfoTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
getDbInfo();
}
public static void getDbInfo(){
Connection conn=null;
DatabaseMetaData dbmd=null;
ResultSet rs=null;
ResultSet rs2=null;
conn=DbUtils.getConnection();
try {
dbmd=conn.getMetaData();//
System.out.println(" :"+dbmd.getDatabaseProductName());
System.out.println(" :"+dbmd.getDatabaseProductVersion());
rs=dbmd.getTables("", "", "%", new String[]{"TABLE","VIEW"});
while(rs.next()){
int i=1;
String cat=rs.getString(i++);
String schema=rs.getString(i++);
String tableName=rs.getString(i++);
String tableType=rs.getString(i++);
System.out.println(cat+","+schema);
System.out.println(" :"+tableName+", :"+tableType);
rs2=dbmd.getColumns("", "", tableName, "%");
while(rs2.next()){
String columnName=rs2.getString(4);
int type=rs2.getInt(5);
System.out.println("\t :"+columnName+", :"+getTypeName(type));
}
System.out.println("------------------");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DbUtils.close(rs);
DbUtils.close(conn);// Connection , Statement, statement , ResultSet
}
}
public static String getTypeName(int type){
String str="";
switch(type){
case Types.BIGINT:
case Types.INTEGER:
str="int";break;
case Types.CHAR:
case Types.VARCHAR:
str="String";break;
case Types.BOOLEAN:
str="boolean";break;
case Types.DATE:
case Types.TIME:
case Types.TIMESTAMP:
str="java.util.Date";break;
case Types.BLOB:
case Types.LONGNVARCHAR:
str="java.sql.Blob";break;
case Types.CLOB:
str="java.sql.Clob";break;
}
return str;
}
}