How to run SQL script file on Linux using Java ?

Hi,
I need to execute .sql file using java. I used following approach for this.
private void runScriptEvent(java.awt.event.ActionEvent evt) {                               
        String sqlOutput = "";
        String sqlPromptLines="";
        String currentFunctionName = "";
        if(con!=null){
            String userName = jTextField4.getText();
            String password = jPasswordField1.getText();
            String databaseName = jTextField3.getText();
            try {
                String script_location = "";
                ProcessBuilder processBuilder =null;
                Process process = null;
                //File file = new File("C:/ScriptFile");
                File file = new File("./SQL_Script");
                //File file = new File("E:\\install\\SQL_Script");
                if(file.exists()){
                    File [] list_files= file.listFiles(new FileFilter() {
                                    public boolean accept(File f) {
                                    if (f.getName().toLowerCase().endsWith(".sql"))
                                    return true;
                                    return false;
                int count = 0;
                    for (int i = 0; i<list_files.length;i++){
                        script_location = "@" + list_files.getAbsolutePath();//ORACLE
//currentFunctionName = list_files[i].getName();
StringTokenizer st = new StringTokenizer(list_files[i].getName(), ".");
while(st.hasMoreTokens()) {
currentFunctionName = st.nextToken();
String extention= st.nextToken();
System.out.println("Function Name = "+currentFunctionName + "\t Extention = " + extention);
processBuilder = new ProcessBuilder("sqlplus",userName+"/"+password+"@"+databaseName, script_location); //ORACLE
processBuilder.redirectErrorStream(true);
process = processBuilder.start();
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String currentLine = null;
while ((currentLine = in.readLine()) != null) {
sqlPromptLines = " "+sqlPromptLines + currentLine +"\n";
count ++;
System.out.println(count+" " + currentLine);
if(currentLine.equalsIgnoreCase("Function created.")){
sqlOutput = "\n" sqlOutput currentFunctionName + " " currentLine"\n" ;
break;
}// end while
in.close();
process.destroy();
}//end for
}//end if file exists
} catch (IOException e1) {
jTextArea1.setText(e1.getMessage());
System.out.println("Script Done");
jTextArea1.append(sqlOutput);
}// end id Connection is not null
Above code working appropriate on Windows but not on Linux.
is there any changes needed ?
Regards,
Ajay
Edited by: Ajay Sharma on Nov 21, 2012 6:43 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Hi gimbal2,
about code
jTextArea1.setText(e1.getMessage());I am using this code so that the user will be prompted with a message rather than stack trace.
About the issue I am getting on linux i believe its because of following statement.
processBuilder = new ProcessBuilder("sqlplus",userName+"/"+password+"@"+databaseName, script_location); //ORACLERegards,
Ajay
Edited by: Ajay Sharma on Nov 23, 2012 12:05 PM
Edited by: Ajay Sharma on Nov 23, 2012 12:06 PM

Similar Messages

  • Open a PDF file in linux using java

    Hi..
    How can I open a PDF file in linux using java.
    I am able to open PDF in windows and mac using this code
    in Windows
    Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + path_of_PDF);
    in mac
    Runtime.getRuntime().exec("open " + path_of_PDF);
    But nothing is working with linux.
    Please help
    Thanks

    One thread is enough:
    http://forum.java.sun.com/thread.jspa?threadID=5267458

  • Open PDF file in linux using java

    Hi..
    How can I open a PDF file in linux using java.
    I am able to open PDF in windows and mac using this code
    in Windows
    Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + path_of_PDF);
    in mac
    Runtime.getRuntime().exec("open " + path_of_PDF);
    But nothing is working with linux.
    Please help
    Thanks

    appi wrote:
    Hi.. I found the JDIC binary files. There are different binaries for all the plateform. Is there any solution which is independent of plateform.Yes, and we already told you: Use JDK6, which has those libraries built into the standard class library.
    How can I use these binaries in my existing project. does it work, If I place them at same place where other .class files are kept.Read the documentation of the JDIC project. I'm sure they answer this question in their FAQ.

  • Reg: How to Run a Script File in WebLogic Server 10.3.3

    Hi WebLogic Experts,
    In our project we are using WebLogic Serve 10.3.3. I need to run one script file. could you please suggest me where should i need to place that script file in WebLogic Server 10.3.3 and How to run & stop that Script file.?
    please experts i waiting for your's reply..
    Thanks & Regards,
    Induja..

    1. You can put a command line into startWebLogic.sh to start your script file.
    2. In your proyect you can create a java class to run the script file.
    3. You can create a java class to run the script file an setup it like a startup class into weblogic server.
    4. You can create a java class to run the script file an setup it like a job scheduler into weblogic server.
    In what time you need run this script file?

  • Running sql script files to re create database

    We have having around 10 sql script file that has sql statments inside it (example insert .... delete...update.... etc).Right now what we do is that in jdbc we open each script file, and read each line ,and then make jdbc call run jdbc for each sql statement inside the file.
    Wondering if there is a better way to do this.
    Right now the challenges are
    1)The process goes wrong if there is an extra semi colon ...or extra space after a statments...etc...Basically I find this way of creating data odd...
    2)it is slow because of the network traffic between application server and database server for every sql statements that gets executed.The solution for this issue is to do a batch update....But still I dont like this solution.
    Can someone give me any better idea.
    I am thinking to have all this sql script moved to a store procedure (rather than inside the sql script file) .JDBC then can pick this store procedure sql file ,and create this store procedure via jdbc, and then execute this store procedure.
    This will be faster because all the sql will be running in the databsase.Only one trip to database to call this store procedure.
    Is this a good idea ?
    thx
    m

    Manjit wrote:
    We have having around 10 sql script file that has sql statments inside it (example insert .... delete...update.... etc).Right now what we do is that in jdbc we open each script file, and read each line ,and then make jdbc call run jdbc for each sql statement inside the file.
    Wondering if there is a better way to do this.
    Right now the challenges are
    1)The process goes wrong if there is an extra semi colon ...or extra space after a statments...etc...Basically I find this way of creating data odd...
    2)it is slow because of the network traffic between application server and database server for every sql statements that gets executed.The solution for this issue is to do a batch update....But still I dont like this solution.
    Can someone give me any better idea.
    I am thinking to have all this sql script moved to a store procedure (rather than inside the sql script file) .JDBC then can pick this store procedure sql file ,and create this store procedure via jdbc, and then execute this store procedure.
    This will be faster because all the sql will be running in the databsase.Only one trip to database to call this store procedure.
    Is this a good idea ?
    thx
    mI'm not 100% sure i follow (it's Friday and i have a mild case of ADD).
    Are you suggesting having the Java application create procedures in the database on the fly? If so i would say that's not a good idea.
    Create the stored procedures in the database, have Java call them as needed to process data.
    If you need to load copious amounts of data, look in to external tables, it's possible they could come in handy for what you are doing .... or not ... again, it's hard to say given i find your description of what's currently happening somewhat confusing.

  • How to run sql scripts using batch file for a web dynpro data dictionary

    Hi,
    I want to develop a sql script to be executed on the server alongwith the installation of a product to pre-populate web dynpro data dictionary tables required for the application.
    I further require to make the scripts independent of the database name,so that it can be run at any client environment.
    Your help will be appreciated and rewarded.

    See shoblock's answer
    call sql script from unix
    masterfile.sql:
    @file1 &1
    @file2 &2
    @file3 &3
    @file4 &4
    then just call the master script:
    sqlplus userid/password @masterfile <p1> <p2> <p3> <p4>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • How to output executable Bin file under linux from java

    Hi
    im beginner in java under linux and i want to out put my java programs to be bin files that can run
    if this not possilble
    how to run the output jar files with just double click ?
    does i have to run sh file that do the hob how?
    thanks in advance.

    say your main method (application's entry point) is located in a class com.my.Class,
    then first you create a text file (say, manifest.txt) that contains this line:
    Main-Class: com.my.Class
    [/code}
    and then you append this to the jar's manifest as such:
    jar cfm yourjarfile.jar manifest.txt [additional files you might want to add]
    for more info,
    http://java.sun.com/docs/books/tutorial/deployment/jar/manifestindex.html                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to get free disk space in linux   Using JAVA program ?

    Hi,
    I am new to such adavance topics.. like JNI
    I have to check linux system free disk space , if space is more than 80% it should email to user.
    But how to check that Using Java program ??
    can u give me one sample example ? i will do it if u can do some for me
    thanks
    give me possible solutions...

    Using the Runtime class you can execute any linux command. Check it out.

  • How to convert from xml file to html using java code

    How to convert from xml file to html file using java code

    Get yourself Apache Xalan or Saxon or some XSLT processor
    String styleSheet = "/YourXSLTStylesheet.xsl";
    String dataSource = "/YourXMLDocument.xml";
    InputStream stylesheetSource = TransformMe.class.getResourceAsStream(styleSheet);
    InputStream dataSourceStream = TransformMe.class.getResourceAsStream(dataSource);
    OutputStream transformedOut = new FileOutputStream("filename.html");
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer(new StreamSource(stylesheetSource));
    transformer.transform(new StreamSource(dataSourceStream), new StreamResult(transformedOut));You'll also need to learn XSLT if you don't already know that. Here's a good place to start
    http://www.w3schools.com/xsl/

  • How to read a .csv file(excel format) using Java.

    Hi Everybody,
    I need to read a .csv file(excel) and store all the columns and rows in 2d arrays. Then I can do the rest of the coding myself. I would like it if somebody could post their code to read .csv files over here. The .csv file can have different number of columns and different number of rows every time it is ran. The .csv file is in excel format, so I don't know if that affects the code or not. I would also appreciate it if the classes imported are posted too. I would also like to know if there is a way I can recognize how many rows and columns the .csv file has. I need this urgently so I would be very grateful to anybody who has the solution. Thanks.
    Sincerely Taufiq.

    I used this
    BufferedReader in = new BufferedReader (new FileReader ("test.csv"));
    // and                
    StringTokenizer parser = new StringTokenizer (str, ", ");
                    while (parser.hasMoreTokens () == true)
                    { //crap }works like a charm!

  • How to change locale of keyboard in linux using java.

    In my application I have a JTextArea . In that field i have to call my language dependent keyboard. How to do this?. I tried with InputContext ipt = InputContext.getInstance();
    ipt.selectInputMethod(new Locale("en", "US"))But it is working in windows, but not in linux.

    If any one have experience in this, please respond...

  • Is it Possible to Run SQL Script from Java prog

    Hello
    Is there any API by which we can run SQl Script file ,
    Just by giving database configration parameters and SQL Script file Path ,it will execute that script automatically

    You can excute SQL statemetns throught JDBC, but that doesn't have a facility to read those statements from a file. You'd have to write code to read the file and create and execute statements through JDBC. That should be pretty straightforward though.
    It's conceivable that there's a third party library out there that does it, if you know what to look for.
    If you're not familiar with JDBC, check out http://java.sun.com/developer/onlineTraining/Database/JDBC20Intro/

  • How can I run a SQL script file...

    How can I run a SQL script file from a location on my computer without providing the whole path?
    Is there some way I can set a "Working folder" in SQL Plus??
    Thanks!
    Tom

    You can create an environment variable called "SQLPATH" which is a list of directories that SQL*Plus will search for your .SQL
    scripts.
    I would like to use another directory than the oracle/bin...
    How can I do this ??
    Hello,
    U can do this by this way:
    Save odm_script.sql file to the default Oracle
    directory i.e. Oracle-Home/bin and Run following command
    through SQL Plus.
    SQL>@Script_Name
    I hope this will resolve ur problem.
    Regards,
    Omer Saeed Khan.

  • How to run SQL files from Java?

    Hi,
    Can someone point me towards a link on how to run sql files in Java? Thanks.
    P.S...if I've been completely blind please go easy on me!

    Sorry forgot the formating code thingy
    public static boolean executeScript(File script, Connection conn){
        boolean success = true;
        success = script.exists();
        if(success){
          DEBUG.print("ES::READING SCRIPT:" + script.getAbsolutePath());
          StringBuffer buffer = new StringBuffer();
          success=readScript(script,buffer);
          if(success){
            try{
              String creationScript = buffer.toString();
              Statement st = conn.createStatement();
              int start = 0;
              int end = 0;
              while (end != -1 && start < creationScript.length()) {
                end = creationScript.indexOf("GO", start);
                if (end != -1) {
                  DEBUG.print(creationScript.substring(start, end));
                  st.executeUpdate(creationScript.substring(start, end));
                  start = end + 2; //2 is the length of "GO"
              st.close();
            }catch(Exception e){
              success=false;
              DEBUG.printStackTrace(e);
        }else{
          DEBUG.print("ES::SCRIPT FILE DOES NOT EXISTS");
          success=false;
        return success;
      public static boolean readScript(File script, StringBuffer buffer){
        boolean success = true;
        DEBUG.print("RS:: reading file :" + script.getAbsolutePath());
        try{
          InputStreamReader isr = new InputStreamReader(new FileInputStream(script),"UTF16");
          int ch;
          while ( (ch = isr.read()) > -1) {
            buffer.append( (char) ch);
          if (isr != null)
            isr.close();
        }catch(Exception e){
          success=false;
          DEBUG.printStackTrace(e);
        return success;
      }

  • How to run .sql file in tsql or powershell

    Hi All,
    HOw to run .sql file inside the TSQL or powershell using with IF else condition. This below query works fine but when i executing through the SQL Agent it's geeting an error.Please could help how to run through the SQL agent already using execution type
    in agent as 'Operating system(CmdExec)'
    Declare @computerName varchar(100), @InstanceName varchar(50)                             
    SET @ComputerName = REPLACE(CAST(SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS varchar),'\','$')  
    SET @InstanceName = REPLACE(CAST(SERVERPROPERTY('instancename') AS varchar),'\','$')
    IF (@InstanceName = 'SQL2008R2')
    Begin  
    :r C:\BackupFolder\Test1.sql    
    :r C:\BackupFolder\Test2.sql    
    End
    IF (@InstanceName = 'SQLINS2')
    BEGIN
    :r C:\BackupFolder\Test3.sql
    END
    IF (@InstanceName = 'SQL2012')
    BEGIN
    :r C:\BackupFolder\Test4.sql
    END
    Thansk in Advance
    A-ZSQL

    In T-SQL, you can try using sqlcmd to invoke sql file
    if @@SERVERNAME='abcd'
    begin
    Master..xp_cmdshell 'sqlcmd -S <ServerName> -i BackupDetails.sql -E'
    end
    OR 
     PowerShell 
    Load the snapins
    Add-PSSnapin SqlServerCmdletSnapin100
    Add-PSSnapin SqlServerProviderSnapin100
    Function Get-SqlInstances {
    Param($ServerName = '.')
    $localInstances = @()
    [array]$captions = gwmi win32_service -computerName $ServerName | ?{$_.Name -match "mssql*" -and $_.PathName -match "sqlservr.exe"} | %{$_.Caption}
    foreach ($caption in $captions) {
    if ($caption -like "MSSQLSERVER") {
    $localInstances += $ServerName
    } else {
    $temp = $caption | %{$_.split(" ")[-1]} | %{$_.trimStart("(")} | %{$_.trimEnd(")")}
    $localInstances += "$ServerName\$temp"
    $localInstances
    $instance=Get-SqlInstances -ServerName HQDBSP17
    foreach($i in $instance)
    if($i -like 'CRM2011')
    write-host 'CRM Database'
    invoke-sqlcmd -inputfile 'F:\PowerSQL\test.sql' -ServerInstance 'abcd'
    if( $i -like 'SQL2012')
    write-host 'SQL 2012 instance'
    invoke-sqlcmd -inputfile 'F:\PowerSQL\test.sql' -ServerInstance 'abcd'
    --Prashanth

Maybe you are looking for

  • How to get all the values from a HashMap? thanks

    hi can anyone tell me how to get all the keys and their values contained in a HashMap? thanks

  • Error Message processing IB X12 5010 850

    Can anyone tell me what is causing this error when processing an IB 850? Which .ecs file is trying to find the value of 00501 and why does it not show up in the list as a valid option? Bill Machine Info: (train9) Element ISA12 is a coded list element

  • Financial Reports - chart formatting questions

    1) Is it possible to display the legend label names horizontally? The default lists them vertically and I don't see an option to change this. 2) Is it possible to display axis numeric data labels with a decimal place? 3) Is there any way to have axis

  • Can I run automatically another report after a runned report?

    Hi. Can I run automatically in another report after a runned report? Like: I open a report, I click on Run/View and then the pdf is on screen BI Publisher runs another report (on screen)? Thank you, bye R. Edited by: user12003776 on May 18, 2011 5:29

  • A Problem in executing svrmgrl (R. 8.1.6.1.0, RedHat 7.2, intel)

    Dear Oracle gurus. i'm suffering from ORA-03113 error - with defunct process - in execution of svrmgrl. (i've to install R.8.1.6.1.0 on RedHat 7.2.) like this.... [ora816@encdb ora816]$ svrmgrl Oracle Server Manager Release 3.1.6.0.0 - Production Cop