import java.sql.*;
/**
* <p>Title: 結果集元數據</p>
* <p>Description: 使用結果集元數據對象獲取數據庫信息。</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: JDBCResultMeta.java</p>
* @version 1.0
*/
public class JDBCResultMeta {
private String url="";
private String username="";
private String password="";
/**
*<br>方法說明:主方法
*<br>輸入參數:
*<br>返回類型:
*/
public static void main(java.lang.String[] args) {
if(args.length!=4){
System.out.println("use: java JDBCResultMeta url username password tablename");
return;
}
JDBCResultMeta JRM = new JDBCResultMeta();
JRM.url = args[0];
JRM.username=args[1];
JRM.password=args[2];
JRM.getMeta(JRM.conn(),args[3]);
}
/**
*<br>方法說明:獲得數據連接
*<br>輸入參數:
*<br>返回類型:Connection 連接對象
*/
public Connection conn(){
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(url, username, password);
return con;
}catch(ClassNotFoundException cf){
System.out.println("can´t find class"+cf);
return null;
}catch(SQLException sqle){
System.out.println("can´t connection db:"+sqle);
return null;
} catch (Exception e) {
System.out.println("Failed to load JDBC/ODBC driver.");
return null;
}
}
/**
*<br>方法說明:獲取結果集元數據信息
*<br>輸入參數:Connection con 數據庫連接
*<br>輸入參數:String table 表名稱
*<br>返回類型:
*/
public void getMeta(Connection con, String table){
try {
Statement Stm = con.createStatement();
String sql="select * from "+table;
ResultSet rs = Stm.executeQuery(sql);
ResultSetMetaData lineInfo = rs.getMetaData();
System.out.println("*********************RESULT META Comment************************");
//獲取數據列數
int columnCount = lineInfo.getColumnCount();
System.out.println("Column Count :"+columnCount);
//獲取數據列類型
for(int i=1;i<columnCount+1;i++){
String columeName = lineInfo.getColumnName(i);
String columeType = lineInfo.getColumnTypeName(i);
boolean autocol = lineInfo.isAutoIncrement(i);
System.out.println(columeName+" = "+columeType +" ::: "+autocol);
}
}catch (SQLException se) {
// 輸出數據庫連接錯誤信息
System.out.println("SQL Exception: " + se.getMessage());
se.printStackTrace(System.out);
}catch(Exception e){
System.out.println(e);
}finally{
try{
con.close();
}catch(SQLException se){}
}
}
}