您的位置:首页 > 编程语言 > Java开发

java调用sqlplus执行批量脚本获得输出结果和调用.bat文件

2018-03-05 10:42 966 查看
//FileOutputStream fos = null;
        InputStream in = null;
Process p = null;
//BufferedReader br=null;
InputStreamReader isr=null;

StringBuffer sb = new StringBuffer();

sb.append(sqlPlus+"\\sqlplus ");
//sb.append(username);
if(username.toUpperCase().contains("SYS")){
String[] s=username.split(" ");
sb.append(s[0]);
sb.append("/");
sb.append(password+" ");
sb.append(s[1]+" "+s[2]);
}else{
sb.append(username);
sb.append("/");
sb.append(password);
}
//sb.append("/");
//sb.append(password);
sb.append("@");
//host示例:127.0.0.1:1521/orcl
sb.append(host);
sb.append(" @");
sb.append(sqlScriptPath);
String cmd = sb.toString();
Runtime rt = Runtime.getRuntime();
p = rt.exec(cmd);
in = p.getInputStream();
/*String logPath="D:\\sql.txt";
File file = new File(logPath);
if (!file.exists()) {
file.createNewFile();
}
fos = new FileOutputStream(logPath,false);
//预防脚本名为中文,在log里乱码
OutputStreamWriter oStreamWriter =new OutputStreamWriter(fos,"GBK");
String s="\r\n------------------------------"+sqlScriptPath+"-----------------------------";
oStreamWriter.write(s);
oStreamWriter.flush();
text.append("正在执行文件:"+sqlScriptPath);*/
isr= new InputStreamReader(in, Charset.forName("GBK"));
char[]  b  =  new  char[4096];  
int  n=-1;
            while((n  =  isr.read(b))  !=  -1){
            String str = new String(b, 0, n);
            int i = str.indexOf("SP2-0310");
int j = str.indexOf("SQL>");
//fos.write(str.getBytes(), 0, n);
System.out.println(str);
//text.append(str+"\r\n");
if(str.contains("ORA")){
p.destroy();
throw new MyException("执行该脚本失败");

}
if (i != -1) {
p.destroy();
System.out.println("执行中断:" +sqlScriptPath+ str+"\n");
}
if (j != -1) {
p.destroy();
System.out.println("成功执行"+sqlScriptPath+"\n");
}
            }
/*byte[] b = new byte[4096];
int br = 0;
while ((br = in.read(b)) != -1) {
String str = new String(b, 0, br);
String s=new String(str.getBytes("US-ASCII"),"gbk");
int i = str.indexOf("SP2-0310");
int j = str.indexOf("SQL>");
//fos.write(b, 0, br);
System.out.println(s);
if (i != -1) {
p.destroy();
System.out.println("执行中断:" +sqlScriptPath+ str);
}
if (j != -1) {
p.destroy();
System.out.println("成功执行"+sqlScriptPath);
}
}*/
p.waitFor();
//fos.flush();
//fos.close();
isr.close();
//br.close();
in.close();
p.destroy();

try {
/*if (br != null) {
br.close();
}*/
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}

}
java调用.bat文件:
                Runtime.getRuntime().exec("rundll32 url.dll FileProtocolHandler file://" + path);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: