How to display sqlplus result in java?

22 篇文章 0 订阅

Use the streams provide by the Process returned by the exec.
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Process.html

Process p = Runtime.getRuntime().exec("sqlplus user/pwd@connect @test.sql"); 
OutputStream os = p.getOutputStream();

This code launches sql*plus and runs the script in the 'filename' variable. It displays the results in NetBeans console.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.File;
import java.util.Map;
 
public class test1 {
 
    public static void main (String args []) {
 
        test_script();
    }
 
    public static void test_script () {
 
        String fileName = "@test_table.sql";
        String sqlPath = "E:\\";
 
        String sqlCmd = "sqlplus";
 
        String arg1   = "user/password@sid"; -- plug in your user, password and db name
        String arg2   = fileName;
        try {
            String line;
            ProcessBuilder pb = new ProcessBuilder(sqlCmd, arg1, arg2);
            Map<String, String> env = pb.environment();
            env.put("VAR1", arg1);
            env.put("VAR2", arg2);
            pb.directory(new File(sqlPath));
            pb.redirectErrorStream(true);
            Process p = pb.start();
          BufferedReader bri = new BufferedReader
            (new InputStreamReader(p.getInputStream()));
          BufferedReader bre = new BufferedReader
            (new InputStreamReader(p.getErrorStream()));
          while ((line = bri.readLine()) != null) {
            System.out.println(line);
          }
          bri.close();
          while ((line = bre.readLine()) != null) {
            System.out.println(line);
          }
          bre.close();
          System.out.println("Done.");
        }
        catch (Exception err) {
          err.printStackTrace();
        }
 
    }
 
}

Here is the contents of the script placed at E:
test_table.sql

Prompt drop TABLE ANOTHER_TEST;
DROP TABLE ANOTHER_TEST CASCADE CONSTRAINTS
/ 
 
Prompt Table ANOTHER_TEST;
CREATE TABLE ANOTHER_TEST
(
  BATCH_SEQ             NUMBER,
  BATCH_GROUP_ID        NUMBER,
  STATUS_FLAG           VARCHAR2(30 BYTE),
  OBJ_BEING_PROCESSED   VARCHAR2(80 BYTE),
  BATCH_RUN_START_DTTM  DATE,
  BATCH_RUN_END_DTTM    DATE,
  CREATE_DTTM           DATE,
  CREATE_USER           VARCHAR2(30 BYTE),
  UPDATE_DTTM           DATE,
  UPDATE_USER           VARCHAR2(30 BYTE)
)
LOGGING 
NOCOMPRESS 
NOCACHE
PARALLEL ( DEGREE DEFAULT INSTANCES DEFAULT )
MONITORING
/ 
 
COMMENT ON TABLE ANOTHER_TEST IS 'This is a test table.'
/ 
 
EXIT
/ 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值