在實際項目中,經常會遇到通過JDBC串連資料庫,擷取資料庫及其表資訊的情況,通過這種方法可以使Java程式獨立於資料庫結構,實現異構資料庫件的資料交換。在學習過程中看到一段不錯的代碼,特此轉過來和大家分享,共同學習。感謝原作者。
ConnDB db=new ConnDB();
if(db.connect()){
try {
DatabaseMetaData dbmd=db.conn.getMetaData();
int cols=0; //列數
//建立資料庫
String databaseSql="CREATE DATABASE TESTDATABASE";
db.update(databaseSql);
//庫名
System.out.println("database name:");
ResultSet rest=dbmd.getCatalogs();
while(rest.next()){
System.out.print(rest.getString("TABLE_CAT")+" | ");
}
System.out.println(); //換行
//建立表
rest=dbmd.getTables(db.conn.getCatalog(), null, "testTable", new String[]{"TABLE"});
if(rest.next()){
//testTable already exists
}else{
String createSql="CREATE TABLE testTable(id int primary key auto_increment,name varchar(20))auto_increment=10";
db.update(createSql);
}
//表名列表
System.out.println("table name:");
rest=dbmd.getTables(
db.conn.getCatalog(), //第一個參數為String 型的DatabaseName
null, null,
new String[]{"TABLE"});
//輸出屬性名稱:TABLE_CAT | TABLE_SCHEM | TABLE_NAME | TABLE_TYPE | REMARKS
ResultSetMetaData rsmd=rest.getMetaData();
int len=rsmd.getColumnCount();
for(int i=0;i<len;i++){
System.out.print(rsmd.getColumnName(i+1)+" | ");
}
System.out.println();
//輸出 table_name
while(rest.next()){
System.out.print(rest.getString("TABLE_NAME")+" | ");
//每行7列
cols++;
if(cols%7==0){
System.out.println();
}
}
System.out.println(); //換行
//print table struct
String sql="select * from testTable";
rest=db.query(sql);
rsmd=rest.getMetaData();
len=rsmd.getColumnCount();
System.out.println("table testTable:");
System.out.printf("%-10s | %-12s | %5s | %4s |/n",
new Object[]{"Field","Type","Null","Key"});
//primary key
rest=dbmd.getPrimaryKeys(null, null, "testTable");
String pri="";
if(rest.next()){
pri=rest.getString("COLUMN_NAME");
}
for(int i=0;i<len;i++){
Object[] arg=new Object[7];
arg[0]=rsmd.getColumnName(i+1); //屬性名稱
arg[1]=rsmd.getColumnTypeName(i+1); //類型
arg[2]=String.valueOf(rsmd.getPrecision(i+1));//長度
if(rsmd.isNullable(i+1) == ResultSetMetaData.columnNullable){
arg[3]="Yes"; //
}else{
arg[3]="No"; //NOT NULL
}
if(pri.equals(arg[0])){
arg[4]="PRI";
}else{
arg[4]="";
}
System.out.printf("%-10s | %-8s(%s) | %5s | %4s |/n", arg);
}
//刪除資料庫
String deleteSql="DROP DATABASE TESTDATABASE";
db.update(deleteSql);
//關閉
rest.close();
db.closeConnect();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("ok");
}
引用自:http://hi.baidu.com/dyccsxg/blog/item/b7a2e52b746588f2e7cd4041.html