java exec() run a db2 import command, wait

2019-09-03 09:42发布

问题:

I used java process run a external command. This command is .bat file with some db2 commands. When I want use the process waiffor() return a result, I can't get anything. The program must be block.

java code:

.....

Runtime rt = Runtime.getRuntime();
Process p = null;     

String command = "db2cmd -c -w -i C:/import1.bat";

p = rt.exec(command);   
p.waitFor();

.....

import1.bat:

@echo off
db2 connect to text_DB user text using tesxt0114  

db2 IMPORT FROM "C:\MVCMSInputFiles\IIS20121224180129.csv" OF DEL METHOD P (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16) MESSAGES "C:\MVCMSInputFiles\20121224180129.log" INSERT INTO BLUEX.BIZ_MACHINE (MACHINE_SSERIALNO, MACHINE_STYPE, MACHINE_SPROJECTID, MACHINE_SCATEGORY, MACHINE_SNAME, MACHINE_SBRAND, MACHINE_SSPOT, MACHINE_SPRODUCEDATE, MACHINE_SSERVPERIOD, MACHINE_SENDDATE, MACHINE_SCONTRACTID, MACHINE_SSERVSTATUS, MACHINE_NSTATUS, MACHINE_SSCID, LOG_SLASTUSER, MACHINE_TSIMPORTTIME) 

db2 connect reset


I also use p.getInputStream() to handle InputStream, but the process always be block by the 3rd command (db2 import.....)

javacode:

Runtime rt = Runtime.getRuntime();
Process p = null;

String command = "db2cmd -c -w -i C:/import1.bat";

p = rt.exec(command);

BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

while ((line = reader.readLine())!= null){              
   System.out.println(line);            
}

reader.close();

while(true){                
    if (p.waitFor() == 0) break;            
}

When I used db2 export... or db2 select * from .... replace the 3rd command. The function waitfor can return a result. The process can't be block.

That's too weird.

回答1:

Mabye you can do like :

Runtime rt = Runtime.getRuntime();
Process p = null;     

String command = "db2cmd -c -w -i C:/import1.bat";

p = rt.exec(command); 
p.getInputStream().close();  
p.waitFor();

holp can help you.



回答2:

I got the answer about this question. reason is : Before the p = rt.exec(command), there is connection object that not commit. so the code like this can run correctly.

.... ...
ConnectionFactory.commit(conn);
p = rt.exec(command); 
... ....