Java从Oracle插入语句获取结果

时间:2019-03-19 14:16:22

标签: java sql oracle

我有一个小而简单的GUI,用户可以在其中粘贴一些oracle插入SQL语句,然后将其提交以插入到数据库中。

我的问题是,如何获取结果状态和/或操作的oracle输出并在GUI上显示?例如,“插入X行”或失败时出现错误(例如,异常堆栈跟踪)?

我的2种相关方法如下-第一种方法从GUI获取SQL命令并调用第二种方法运行语句:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
      String SQL = jEditorPane1.getText();
      jEditorPane1.setText("");
      String[] arraySQL = SQL.split(System.lineSeparator());
      for (String s : arraySQL) {
          System.out.println(s);
      }
      executeSQL(arraySQL);
}

 private void executeSQL(String[] commands) {      
        BasicDataSource dataSource = DatabaseUtility.getDataSource();     
        try (Connection connection = dataSource.getConnection()) {          
            for (String sql : commands) {
                try (PreparedStatement ps = connection.prepareStatement(sql)) {
                    ps.execute();
                }
            }
            connection.commit();           
        } catch (SQLException e) {            
            e.printStackTrace();
        } 
}

2 个答案:

答案 0 :(得分:1)

我的开源程序PLSQL_LEXER也许可以帮助您完成任务。

听起来像您在尝试设置较小版本的SQL Fiddle,这是一项艰巨的任务。尝试拆分,分类和运行SQL语句时,存在大量奇怪的解析问题。我在Java方面无济于事,但是如果您愿意在PL / SQL中完成大部分繁重的工作,那么下面的代码应该会有所帮助。

如果安装软件包,然后在下面创建存储的函数,则只需将字符串(CLOB)传递给Oracle,然后返回结果。

代码还显示了如何防止某些类型的命令运行。但这只是为了方便起见,如果要警告人们不要运行某些事情。您不想在这里尝试重新实现Oracle安全性。您应该假定向该功能提交命令的任何人都具有与拥有该功能的用户相同的特权。

create or replace function run_commands(p_statements clob) return clob
as
    v_split_statements token_table_table;
    v_category         varchar2(100);
    v_statement_type   varchar2(100);
    v_command_name     varchar2(64);
    v_command_type     number;
    v_lex_sqlcode      number;
    v_lex_sqlerrm      varchar2(4000);
    v_output           clob;
begin
    --Tokenize and split the string into multiple statements.
    v_split_statements := statement_splitter.split_by_semicolon(
        plsql_lexer.lex(p_statements));

    --Loop through the statements.
    for i in 1 .. v_split_statements.count loop
        --Classify each statement.
        statement_classifier.classify(
            p_tokens =>         v_split_statements(i),
            p_category =>       v_category,
            p_statement_type => v_statement_type,
            p_command_name =>   v_command_name,
            p_command_type =>   v_command_type,
            p_lex_sqlcode =>    v_lex_sqlcode,
            p_lex_sqlerrm =>    v_lex_sqlerrm
        );

        --For debugging, print the statement and COMMAND_NAME.
        v_output := v_output||chr(10)||'Statement '||i||' : '||
            replace(replace(
                plsql_lexer.concatenate(v_split_statements(i))
            ,chr(10)), chr(9));
        v_output := v_output||chr(10)||'Command Name: '||v_command_name;

        --Handle different command types.
        --
        --Prevent Anonymous Blocks from running.
        if v_command_name = 'PL/SQL EXECUTE' then
            v_output := v_output||chr(10)||'Error       : Anonymous PL/SQL blocks not allowed.';
        --Warning message if "Invalid" - probably a typo.
        elsif v_command_name = 'Invalid' then
            v_output := v_output||chr(10)||'Warning     : Could not classify this statement, '||
                'please check for a typo: '||
                replace(replace(substr(
                    plsql_lexer.concatenate(v_split_statements(i))
                , 1, 30), chr(10)), chr(9));
        --Warning message if "Nothing"
        elsif v_command_name = 'Nothing' then
            v_output := v_output||chr(10)||'No statements found.';
        --Run everything else.
        else
            declare
                v_success_message         varchar2(4000);
                v_compile_warning_message varchar2(4000);
            begin
                --Remove extra semicolons and run.
                execute immediate to_clob(plsql_lexer.concatenate(
                    statement_terminator.remove_semicolon(
                        p_tokens => v_split_statements(i))));
                --Get the feedback message.
                statement_feedback.get_feedback_message(
                    p_tokens => v_split_statements(i), 
                    p_rowcount => sql%rowcount,
                    p_success_message => v_success_message,
                    p_compile_warning_message => v_compile_warning_message
                );
                --Print success message.
                v_output := v_output||chr(10)||'Status      : '||v_success_message;
                --Print compile warning message, if any.
                --This happens when objects successfully compile but are invalid.
                if v_compile_warning_message is not null then
                    v_output := v_output||chr(10)||'Compile warning: '||v_compile_warning_message;
                end if;
            exception when others then
                v_output := v_output||chr(10)||'Error       : '||dbms_utility.format_error_stack||
                    dbms_utility.format_error_backtrace;
            end;
        end if;
    end loop;

    return v_output;
end;
/

下面是运行存储过程和输出的示例。您必须将这个PL / SQL块转换为Java调用,但是我认为这不会太复杂。

declare
    --A collection of statements separated by semicolons.
    --These may come from a website, text file, etc.
    v_statements clob := q'<
        create table my_table(a number);
        insert into my_table values(1);
        begin null; end;
        udpate my_table set a = 2;
    >';
    v_results clob;
begin
    v_results := run_commands(v_statements);
    dbms_output.put_line(v_results);
end;
/

Statement 1 : create table my_table(a number);
Command Name: CREATE TABLE
Status      : Table created.
Statement 2 : insert into my_table values(1);
Command Name: INSERT
Status      : 1 row created.
Statement 3 : begin null; end;
Command Name: PL/SQL EXECUTE
Error       : Anonymous PL/SQL blocks not allowed.
Statement 4 : udpate my_table set a = 2;
Command Name: Invalid
Warning     : Could not classify this statement, please check for a typo: udpate my_table set a = 2;

答案 1 :(得分:0)

使用@KevinO建议使用executeUpdate()方法(以检查插入的记录),并结合使第二方法返回字符串(“成功”或SQLException消息),对我来说很有效