JDBC:调用外部SQL脚本,它声明一个PL / SQL包

时间:2015-03-29 03:35:24

标签: java sql oracle jdbc plsql

我有一个名为setup的SQL脚本,它建立了一些设置,然后声明了一个名为salespack的PL / SQL包

setup.sql:

set verify off
set feedback off
set serveroutput on;
set linesize 200;
@Package/pack.sql
@Package/packbody.sql

我有一个名为main.java的文件,它试图运行上面的SQL脚本,然后调用该包,但这似乎不起作用。如何使用jdbc调用SQL脚本,声明PL / SQL包,然后使用包中的函数。我得到的错误是callstmt.execute();是一个无效的SQL语句。

main.java:

import java.sql.*;
import java.io.*;

class main
{
  public static void main (String args [])
       throws SQLException, IOException
  {
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    String connect = "jdbc:oracle:thin:@vmaddress:1521:xe";
    Connection conn = DriverManager.getConnection (connect, "user", "pass");

    //Perform setup
    //Load packages, allow output, establish sale database
    //Make sure to run the main script from dbSetup to have fresh data
    CallableStatement callstmt = conn.prepareCall ("@setup.sql");
    callstmt.execute();
    callstmt.close();

    CallableStatement callstmt2 = conn.prepareCall ("{ ? = call salepack.getspname(?) }");
    callstmt2.registerOutParameter (1, Types.VARCHAR);
    int id = 23;    // the id is hard-coded here for simplicity
    callstmt2.setInt(2, id);

    callstmt2.execute();
    String name = callstmt2.getString(1);
    System.out.println ("The salesperson with id of " + id + " is " + name);
    callstmt2.close();
    conn.close();
  }
}

1 个答案:

答案 0 :(得分:0)

我认为您可以使用以下代码运行setup.sql

private static String script_location = "";
private static String file_extension = ".sql";
private static ProcessBuilder processBuilder =null;

public static void main(String[] args) {
try {
    File file = new File("C:/sql_folder");
    File [] list_files= file.listFiles(new FileFilter() {

        public boolean accept(File f) {
            if (f.getName().toLowerCase().endsWith(file_extension))
                return true;
            return false;
        }
    });
    for (int i = 0; i<list_files.length;i++){
        script_location = "@" + list_files[i].getAbsolutePath();//ORACLE
        processBuilder = new ProcessBuilder("sqlplus",        "UserName/Password@database_name", script_location); //ORACLE
        //script_location = "-i" + list_files[i].getAbsolutePath();
        //  processBuilder = new ProcessBuilder("sqlplus", "-Udeep-Pdumbhead-Spc-de-deep\\sqlexpress-de_com",script_location);
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String currentLine = null;
        while ((currentLine = in.readLine()) != null) {
            System.out.println(" "  + currentLine);
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}catch(Exception ex){
    ex.printStackTrace();
}
}

也许在链接下面会给你一些其他的想法;

How to display sqlplus result in java?