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;
  }

Similar Messages

  • How to run perl file from java file..???

    Hi All,
    How to run a perl file from java file.I know that there is one JPL(Java-Perl Library) preprocessor which can be used to do this,but no idea of how to do it..
    Any help is appreciated.
    Thanks in advance.

    viswa07 wrote:
    Ok and any idea regarding JPL..????I don't know it and the first few posts that I found mentioned it using Java 1.1-style JNI calls, which hints at a dead project. And you don't want to use a dead project.

  • How to run .html file from .java file..?

    Hi All,
    I was just trying as mentioned in the subject of how to run an html file from a java file.We have runtime class which inturn is having exec method which returns process but it supports only .exe as an argument .Is there any way to do this???
    Thanks in advance.

    viswa07 wrote:
    You mean to say Desktop class in java...???I'm so sorry, I thought you knew enough Java to look up the API.
    [This link|http://java.sun.com/docs/books/tutorial/getStarted/cupojava/index.html] might be more at your level.
    db

  • How to run batch file from oracle forms 9i

    Hi everyone.
    i have a data in csv file. i want to upload it to my database. i am using sql loader for it.
    i have made a batch file which run the sql loader and transfer my data to database.
    How to run batch file from oracle forms 9i.
    when i press the button, nothing uploads in my database. (when i simply run the batch file it works).
    here is my code
    Begin
    HOST('C:\temp\batchfile.bat');
    message('done');
    end;
    Thanks in advance
    regards
    sajid

    this is my log file, when i run manually.
    SQL*Loader: Release 10.2.0.1.0 - Production on Thu Jul 1 23:27:53 2010
    Copyright (c) 1982, 2005, Oracle. All rights reserved.
    Control File: file_to_upload.ctl
    There are 2 data files:
    Data File: sk.csv
    Bad File: sk.bad
    Discard File: none specified
    (Allow all discards)
    Data File: sk1.csv
    Bad File: sk1.bad
    Discard File: none specified
    (Allow all discards)
    Number to load: ALL
    Number to skip: 0
    Errors allowed: 50
    Bind array: 64 rows, maximum of 256000 bytes
    Continuation: none specified
    Path used: Conventional
    Table KHAN, loaded from every logical record.
    Insert option in effect for this table: APPEND
    Column Name Position Len Term Encl Datatype
    SR FIRST * , O(") CHARACTER
    DATES NEXT * , O(") CHARACTER
    AGENT NEXT * , O(") CHARACTER
    COUNTRY NEXT * , O(") CHARACTER
    TRANSACTIONS NEXT * , O(") CHARACTER
    PKR NEXT * , O(") CHARACTER
    USD NEXT * , O(") CHARACTER
    BANK NEXT * , O(") CHARACTER
    Table KHAN:
    11088 Rows successfully loaded.
    0 Rows not loaded due to data errors.
    0 Rows not loaded because all WHEN clauses were failed.
    0 Rows not loaded because all fields were null.
    Space allocated for bind array: 132096 bytes(64 rows)
    Read buffer bytes: 1048576
    Total logical records skipped: 0
    Total logical records read: 11088
    Total logical records rejected: 0
    Total logical records discarded: 0
    Run began on Thu Jul 01 23:27:53 2010
    Run ended on Thu Jul 01 23:27:54 2010
    Elapsed time was: 00:00:00.63
    CPU time was: 00:00:00.17

  • Invoking .SQL file from JAVA

    Hi All,
    Anyway of calling .SQL files from JAVA ??
    thanks in advance..

    What do you mean by calling?
    Are you talking about a stored procedure? Then yes.typo !!
    i meant invoking .SQL script only...
    No not stored procedure..i mean running or invoking a sql file containing sql statements(inserts etc)

  • Running exe files from java applications

    Hello All,
    Is it possible to run executable files from java applications?
    I need to run an exe file on the client from the server machine, the exe could reside on either the server or any other machine on the LAN. Is it possible to specify the path of where the exe resides, and run it on a client machine?

    HI,
    I tried to launch a MS Word application using runtime.exec but it gives me some problem
    The foll. code to launch a txt file using notepad works.
    Runtime rt = Runtime.getRuntime();
    String[] callAndArgs = {"notepad.exe","C:\\coo7\\wizard.txt"};
    Process child = rt.exec(callAndArgs);
    However, oif I try to launch a MS Word application, it asks for the entire path of WINWORD.exe, (unlike just specifying notepad.exe as the first argument in String[] callAndArgs) and this can vary from one machine to another.. how do I get around this?
    The foll. code snippet works but the complete path of where WINWORD.exe might be installed on any machine, is not fixed:-(
    Runtime rt = Runtime.getRuntime();
    String[] callAndArgs = {"C:\\Program Files\\Office\\Office10\\WINWORD.exe","C:\\coo7\\wizard.doc"};
    Process child = rt.exec(callAndArgs);
    Any idea/suggestions pls..

  • How to run ear file in java application server

    i want how to run .ear file in java application server
    1. i m created ear file
    2. i m created jar file (bean,home,remote)
    3.i m created war file(in the form of jsp)
    but till now i couldnt run ear file
    how to run
    please hel me

    You must create :
    1.Jar file
    2.War file
    And then put them into an ear file
    Exemple : myapp.ear contains
    myappEJB.jar
    myappWEB.war
    META-INF/application.xml
    and application.xml looks like this :
    <application xmlns="http://java.sun.com/xml/ns/j2ee" version="1.4"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com /xml/ns/j2ee
                            http://java.sun.com/xml/ns/j2ee/application_1_4.xsd">
        <display-name>myapp</display-name>
        <description>Demo application</description>
        <module>
            <ejb>myappEJB.jar</ejb>
        </module>
        <module>
          <web>
             <web-uri>myappWAR.war</web-uri>
             <context-root>/myapp</context-root>
          </web>
        </module>
    </application>Good luck

  • Running  .nsi file from java

    hi,
    Ho to run .nsi file from java.
    thanks in advance.

    User845466 wrote:
    Ho to run .nsi file from java.Find the program hanling that kind of documents an launch this via Runtime.exec() giving it your *.nsi file as a parameter.
    bye
    TPD

  • 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

  • How to execute sql file from servlet

    Hi,
    I am using JSP, Servlets and Oracle 8i in my application. I want to execute .sql file from java code. Is it possible to do that,
    as we execute .sql file from sql plus prompt.
    Suppose I have abc.sql file and I want to execute it from java code.
    If any body have the solution then pl. reply with sample code.
    Thanks,
    Rajesh

    If any body have the solution then pl. reply with
    sample code.No, no, dec - s/he doesn't want the actual solution, but the full code!
    /k1

  • How to call external files from java?

    How to call external files in java. For example how to call a *.pdf file to open in its default editor(say Acrobat), or a *.html file to open in the default browser or a *.txt file in a notepad etc..,
    In my program i have *.chm (Compiled Windows HTML Help) help file. how to open it in its default editor it?

    Jayarathina_Madharasan wrote:
    no one answered my questionHi what wrong did i do...basically insulted all the volunteers here who took the time to consider your question and try to offer you help. Other than that, you did nothing wrong.
    From JavaRanch :
    And even if an answer doesn't solve your problem, even if it should totally miss the point - the best thing to do to motivate others to continue trying to help you is showing respect and gratitude for the investment of time that was put into dealing with your issue.
    Edited by: Encephalopathic on Apr 14, 2008 10:01 AM

  • Error running batch files from java source file???

    Dear Friends,
    hi,
    this is with response to a doubt i had earlier ,
    i want to run batch files from the java source file ,i tried using this code (here batrun is the batch file name that contains commands to run other java files)
    try
    String [] command = {"c:\\vishal\\finalmain\\batrun"};
    Runtime.getRuntime().exec(command);
    catch(Exception e)
    but i got the following error.
    java.io.IOException: CreateProcess: gnagarrun error= 2
    plz. help me, i tried all combination w/o success,
    in anticipation(if possible give the code after testing)
    Vishal.

    hello there,
    i solved the prob. by using
    cmd /c start filename ,but i need to pass parameters ie
    cmd /c start java "c:/vishal/runfile a b" where a and b are the parameters. but it is not accepting this in Runtime.getRuntime.exec(),
    any solutions ?????????
    regards,
    Vishal

  • How to run ODI scenario from java?

    I am new to java, need to do some testing on how to invoke ODI scenarios from java.
    Can somebody drop me some simple code?
    Thanks a lot,
    Lei

    Hi there
    1. Start your agent (double click agent.bat)
    2. generate scenario for ur package(right click ur package , select generate scenario)
    3. Add the odi-sdk-invocation.jar file to your java project
    ODIcmdScenario=new OdiCommandScenario();
    ODIConnection=new OdiRepositoryConnection();
    ODIConnection.setOdiUser("ur-username");
    ODIConnection.setOdiPassword("ur-password");
    ODIConnection.setJdbcDriver("Driverdetail");
    ODIConnection.setJdbcUrl("url-details");
    ODIConnection.setJdbcUser("dbusername");
    ODIConnection.setJdbcPassword("dbpass");
    ODIcmdScenario.setScenName("scenarioname");
    ODIcmdScenario.setScenVersion("scenarioversion");
    ODIcmdScenario.setLogLevel(5);
    ODIcmdScenario.setContext("context");
    ODIConnection.setWorkRepositoryCode("repository");
    ODIInvocation = new OdiInvocation("hostname", 20910); //20910 default port
    OdiInvocationResult result=ODIInvocation.invokeCommand(ODIcmdScenario,ODIConnection);
    Hope this helps!
    Cheers

  • How to Call .XDO file From Java Program

    Hi,
    I have developed a report in using BI Publisher version 10.1.3.
    I created the report and it only created XDO files. If I want to call XDO file from Java program how I can do that.
    What are the APIs available to do that.
    Thanks
    -Ashutosh

    Hi,
    the JavaAPI didn't work with the xdo-Files. But you can create a proxy stub for the Web Service API of BI Publisher which uses the xdo's in the repository.
    regards
    Rainer

  • How to run exe file from inside java

    I wan to run an exe file from inside java code. How can I do it?
    Thanks

    Hi Oakam
    This is very simple. Just go through the given code below
    in place of FILEANDPATHNAME just give the exe's path and name
    Note :- adding ".exe " is not necessary
    public class exep
    public static void main(String args[])
    Runtime r = Runtime.getRuntime();
    Process p = null;
    try{
    p = r.exec("FILEANDPATHNAME");
    catch(Exception e)
    Give ur feedback
    Thanx
    Ottran

Maybe you are looking for