欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java调用sqlplus执行定制的sql脚本

程序员文章站 2022-05-09 08:48:15
...
package com.sky.read;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class PLSQL {

public static void main(String[] args) {
FileOutputStream fos = null;
InputStream in = null;
Process p=null;
try {
String cmd = "sqlplus gts1031/gts1031@ORACL @init-6.0.01.sql >D:/gts1031.log";
Runtime rt = Runtime.getRuntime();
p = rt.exec(cmd,null,new File("D:/db/integrate/"));
in = p.getInputStream();
fos = new FileOutputStream("D:/gts1031.log");
byte[] b = new byte[1024];
int br = 0;
while ((br = in.read(b)) != -1) {
fos.write(b, 0, br);
}
p.waitFor();
System.out.println("执行结束");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}

}
}

}
p = rt.exec(cmd,null,new File("D:/db/integrate/"));
new File(D:/db/integrate/)指定了子进程的工作目录,这样sql脚本里的引用其他文件是就可以使用相对路径.相当于在cmd下,切换到相映脚本的目录,再执行sqlplus,这样sqlplus执行的sql脚本中引用其他文件时可以使用相对路径
package com.sky.read;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class PLSQL {

public static void main(String[] args) {
new PLSQL().exeSqlplus("gts1031", "gts1031", "ORACL",
"init-6.0.01.sql", "D:/db/integrate/", "D:/DBLOGS/",
"gts1031.log");
}

public void exeSqlplus(String username, String password, String host,
String fileName, String dir, String logdir, String logFileName) {
FileOutputStream fos = null;
InputStream in = null;
Process p = null;
try {
StringBuffer sb = new StringBuffer();
sb.append("sqlplus ");
sb.append(username);
sb.append("/");
sb.append(password);
sb.append("@");
sb.append(host);
sb.append(" @");
sb.append(fileName);
// String cmd =
// "sqlplus gts1031/gts1031@ORACL @init-6.0.01.sql >D:/gts1031.log";
String cmd = sb.toString();
Runtime rt = Runtime.getRuntime();
// p = rt.exec(cmd,null,new File("D:/db/integrate/"));
p = rt.exec(cmd, null, new File(dir));
in = p.getInputStream();
File file = new File(logdir);
if (!file.exists()) {
file.mkdir();
}
// fos = new FileOutputStream("D:/gts1031.log");
fos = new FileOutputStream(logdir + logFileName);
byte[] b = new byte[512];
int br = 0;
while ((br = in.read(b)) != -1) {
String str = new String(b, 0, br);
int i = str.indexOf("SP2-0310");
int j = str.indexOf("SQL>");
fos.write(b, 0, br);
if (i != -1) {
p.destroy();
System.out.println("执行中断:" + str);
}
if (j != -1) {
p.destroy();
System.out.println("成功执行");
}
}
p.waitFor();
fos.flush();
fos.close();
in.close();
p.destroy();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}

}
}
}