日期:2014-05-20 浏览次数:21039 次
package book.database; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; public class GetMetadata { public static void showDatabaseMetadata(Connection con){ try{ DatabaseMetaData md=con.getMetaData(); System.out.println("数据库"+md.getURL()+"的元数据如下:"); }catch (SQLException e){ e.printStackTrace(); } } public static void showTableMetaData(Connection con,String tableName){ String sql="SELECT * FROM"+tableName; Statement sm=null; try{ sm=con.createStatement(); ResultSet rs= sm.executeQuery(sql); ResultSetMetaData md = rs.getMetaData(); System.out.println("数据表"+tableName+"的元数据如下:"); int columnCount = md.getColumnCount(); System.out.println("column count:"+columnCount); System.out.println(); StringBuffer sb =new StringBuffer(""); sb.append("sn\tname\t\t").append("type\t\t"); sb.append("scale\t").append("isNullable"); System.out.println(sb); sb.delete(0, sb.length()); for(int i=1;i<=columnCount;i++){ sb.append(i).append("\t"); sb.append(md.getColumnName(i)).append("\t\t"); sb.append(md.getColumnTypeName(i)).append("\t\t"); sb.append(md.getScale(i)).append("\t"); sb.append(md.isNullable(i)); System.out.println(sb); sb.delete(0,sb.length()); } rs.close(); }catch(SQLException e){ e.printStackTrace(); }finally{ if (sm!= null){ try{ sm.close(); }catch(SQLException e1){ e1.printStackTrace(); } } } } public static void main(String[] args) throws ClassNotFoundException,SQLException{ String dbName = "books"; String tableName = "book"; String userName = "root"; String password = "123456"; Connection con = null; try{ con = DBConnector.getMySQLConnection(null,null,null,dbName,userName,password); GetMetadata.showDatabaseMetadata(con); System.out.println(); GetMetadata.showTableMetaData(con,tableName); }catch (ClassNotFoundException e1){ throw e1; }catch (SQLException e2){ throw e2; }finally { if (con != null){ try{ con.close(); }catch(SQLException e1){ e1.printStackTrace(); } } } } }