2012-03-06 86 views
0

我無法在我的Java程序中檢索"db2 list db directory"命令的輸出。基本上,我試圖做到這一點: -如何從Java程序中檢索db2命令輸出

  1. 組合框在本地系統
  2. 用戶填入DB2實例選擇從組合框
  3. 一個新的進程運行的特定實例列出數據庫中該實例
  4. 顯示數據庫中以另一個組合框

這是我做了一段代碼: -

// dbinstances is a Combo box (Eclipse SWT widget) 

this.dbInstances.addSelectionListener(new SelectionListener() { 

    @Override 
    public void widgetSelected(SelectionEvent arg0) { 

     // get selected instance name 
     String instance = dbInstances.getText(); 

     // command invokes db2 command window, sets current instance and issues list db command 
     String command = "db2cmd /c \"set DB2INSTANCE="+instance+" & db2 list db directory\""; 

     // execute command and read output 
     try{ 
      Process p = Runtime.getRuntime().exec(command); 
      BufferedReader br= new BufferedReader(new InputStreamReader(p.getInputStream())); 
      String op = null; 
      while((op=br.readLine())!=null){ 
       System.out.println(op); 
      } 
     } 
     catch(IOException ioe){ 
      ioe.printStackTrace(); 
     } 
    } 

     public void widgetDefaultSelected(SelectionEvent arg0) {} 
}); 

問題是該命令執行,我無法檢索輸出。窗戶剛剛打開和關閉。

我試過的一個解決方案是將輸出重定向到一個臨時文件並讀取它。它可以工作,但是效率很低,因爲每次用戶選擇一個實例時都會運行這段代碼。

我在Windows XP SP3計算機上運行DB2 9.7企業版。

有關如何檢索Java程序中的輸出的任何想法?

非常感謝。

+0

好了,想通了這一個了。所需的解決方案是將/ w和/ i開關添加到命令中: - 'String command =「db2cmd/c/w/i \」set DB2INSTANCE =「+ instance +」&db2 list db directory \「」;' 更多信息在這裏:http://www.ibm.com/developerworks/data/library/techarticle/0307fierros/0307fierros.html#cw – vaisakh 2012-03-06 09:47:34

回答

1

好的,算出這一個。所需的解決方案是添加/ w和/我切換到命令: -

// command invokes db2 command window, sets current instance and issues list db command 
String command = "db2cmd /c /w /i \"set DB2INSTANCE="+instance+" & db2 list db directory\""; 

根據IBM developerWorks

// Additional information about db2cmd Options 
-c Execute the DB2 command window and terminate. 
-w Wait until the DB2 command window terminates. 
-i Inherit the environment from the invoking shell. 
-t Inherit the title from the invoking shell 
+0

它只適用於Windows。 – AngocA 2014-04-30 10:27:28

1

您還可以通過JNI,以便檢索數據庫列表使用DB2 API目錄。您必須開始掃描,獲取條目,然後關閉掃描。通過這樣做,您可以更好地控制數據庫列表,解析可能由多種原因(HADR,身份驗證機制,本地或遠程,帶或不帶別名,IP地址或服務器名稱,服務名稱或端口號,在Linux(主目錄)或Windows(驅動器號)中,以及其他內容) DB2 API在所有平臺中都是相同的,所以它幾乎是平臺獨立的,您只需知道哪個庫負載(.so或.dll),但其餘部分是相同的。

欲瞭解更多信息,看一看: db2DbDirOpenScan http://publib.boulder.ibm.com/infocenter/db2luw/v9r7/topic/com.ibm.db2.luw.apdv.api.doc/doc/r0001509.html db2DbDirGetNextEntry http://publib.boulder.ibm.com/infocenter/db2luw/v9r7/topic/com.ibm.db2.luw.apdv.api.doc/doc/r0001492.html db2DbDirCloseScan http://publib.boulder.ibm.com/infocenter/db2luw/v9r7/topic/com.ibm.db2.luw.apdv.api.doc/doc/r0001437.html

+1

更好的是,嘗試直接在Java中使用JNA,一個JNI包裝器。 – AngocA 2012-03-07 14:26:01

+0

謝謝,這對我來說是新的.. :)然而,我認爲,對於這個微不足道的目的,JNI可能是一個矯枉過正的問題。 – vaisakh 2012-03-08 08:34:51