Can we execution  sql script through java ?

Hi All,
Can we execute sql script ("name.sql") through java programe.
I am not talking about reading sql script one by one and excute.
I just want to send this sql script to oracle console.
Or any body can give other alternative I have to lot of db operation in less time.
- Vikas Kumar Sahu

Kumar,
not sure whether this is any help, but you can try and use the code below.
I've knocked it together in about an hour so it's far from production ready (particularly, assumes one-line comments starting with '#' and nothing else - queries are assumed multi-line, but terminated by ';' the following would cause trouble:
SELECT * FROM table; SELECT *
FROM another_table;
and, of course, you can't get to the ResultSet.
But, hey, it's a start!
Best,
Marco.
(www.infinitebw.com)
admin (at) infinitebw.com
package com.ibw.database;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import com.ibw.exception.DatabaseException;
public class SqlScript {
     public final static char QUERY_ENDS = ';';
     private File script;
     private Connection conn;
     private Statement stat;
     * @param args
     * @throws SQLException
     public SqlScript(String scriptFileName) throws SQLException {
          script = new File(scriptFileName);
// this is a 'custom' class, just use instead getConnection() from the
// DriverManager instead
          conn = ConnectionManager.getConn("test");
          stat = conn.createStatement();
     public static void main(String[] args) {
          try {
               SqlScript sqlScript = new SqlScript("C:/temp/myscript.sql");
               sqlScript.loadScript();
               sqlScript.execute();
          } catch (SQLException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
     protected void loadScript() throws IOException, SQLException {
          BufferedReader reader = new BufferedReader(new FileReader(script));
          String line;
          StringBuffer query = new StringBuffer();
          boolean queryEnds = false;
          while ((line = reader.readLine()) != null) {
               if (isComment(line))
                    continue;
               queryEnds = checkStatementEnds(line);
               query.append(line);
               if (queryEnds) {
                    stat.addBatch(query.toString());
                    query.setLength(0);
     private boolean isComment(String line) {
          if ((line != null) && (line.length() > 0))
               return (line.charAt(0) == '#');
          return false;
     public void execute() throws IOException, SQLException {
          stat.executeBatch();
     private boolean checkStatementEnds(String s) {
          return (s.indexOf(QUERY_ENDS) != -1);
}

Similar Messages

  • Exceuting SQL Script through java

    Hi All
    I am making an installer for my application. How do i execute a SQL script through java. Its a sepeate file that has the SQL script for DB creation.
    Regards
    Abhinav

    If you database support ";" to separate sqll, then you can use Statement.execute(sql); to run all SQLscipt once, otherwise you need to load all sqls into Vector, then reun sql step by step. Copy some code for instance:
    public final static Object[] getSQLStatements(String sqlFile) throws java.
    io.IOException {
    java.util.Vector v = new java.util.Vector(1000);
    try {
    java.io.BufferedReader br = new java.io.BufferedReader(new java.io.
    FileReader(sqlFile));
    java.util.Vector batchs = new java.util.Vector(10);
    String temp;
    while ( (temp = br.readLine()) != null) {
    temp = temp.trim();
    if (temp.length() == 0)
    continue;
    switch (temp.charAt(0)) {
    case '*':
    case '"':
    case '\'':
    // System.out.println(temp);
    break; //Ignore any line which begin with the above character
    case '#': //Used to begin a new sql statement
    if (batchs.size() > 0) {
    v.addElement(getSQLStatements(batchs));
    batchs.removeAllElements();
    break;
    case 'S':
    case 's':
    case '?':
    if (batchs.size() > 0) {
    v.addElement(getSQLStatements(batchs));
    batchs.removeAllElements();
    v.addElement(temp);
    break;
    default:
    batchs.addElement(temp);
    break;
    if (batchs.size() > 0) {
    v.addElement(getSQLStatements(batchs));
    batchs.removeAllElements();
    br.close();
    br = null;
    catch (java.io.FileNotFoundException fnfe) {
    v.addElement(sqlFile); //sqlFile is a sql command, not a file Name
    Object[] statements = new Object[v.size()];
    for (int i = 0; i < v.size(); i++)
    statements[i] = v.elementAt(i);
    return statements;
    for (int i = 0; i < statements.length; i++) {
    if (statements[i] instanceof java.lang.String) {
    String temp = (java.lang.String) statements;
    switch (temp.charAt(0)) {
    case 'S':
    case 's':
    case '?':
    System.out.println(temp);
    rs = stmt.executeQuery(temp);
    ResultSetMetaData resultSetMetaData = rs.
    getMetaData();
    int iNumCols = resultSetMetaData.getColumnCount();
    for (int j = 1; j <= iNumCols; j++) {
    System.out.println(resultSetMetaData.getColumnLabel(j)
    + " " + resultSetMetaData.getColumnTypeName(j)
    + " " + resultSetMetaData.getColumnType(j)
    + " " + resultSetMetaData.getPrecision(j)
    + " " + resultSetMetaData.getScale(j)
    Object colval;
    long ncount = 0;
    while (rs.next()) {
    // System.out.print(rs.rowDeleted()+" ");
    ncount++;
    for (int j = 1; j <= iNumCols; j++) {
    colval = rs.getObject(j);
    System.out.print(colval + " ");
    System.out.println();
    rs.close(); //Let the CONCUR_UPDATABLE resultSet release its open files at once.
    rs = null;
    System.out.println(
    "The total row number of resultset: " + ncount);
    System.out.println();
    break;
    default:
    int updateCount = stmt.executeUpdate(temp);
    System.out.println(temp + " : " + updateCount);
    System.out.println();
    else if (statements[i] instanceof java.lang.Object[]) {
    int[] updateCounts;
    Object[] temp = (java.lang.Object[]) statements[i];
    try {
    for (int j = 0; j < temp.length; j++){
    System.out.println( temp[j]);
    stmt.addBatch( (java.lang.String) temp[j]);
    updateCounts = stmt.executeBatch();
    for (int j = 0; j < temp.length; j++)
    System.out.println((j+1)+":"+temp[j]);
    for (int j = 0; j < updateCounts.length; j++)
    System.out.println((j+1)+":" +updateCounts[j]);
    catch (java.sql.BatchUpdateException e) {
    updateCounts = e.getUpdateCounts();
    for (int j = 0; j < updateCounts.length; j++)
    System.out.println((j+1)+":"+updateCounts[j]);
    java.sql.SQLException sqle = e;
    do {
    System.out.println(sqle.getMessage());
    System.out.println("Error Code:" +
    sqle.getErrorCode());
    System.out.println("SQL State:" + sqle.getSQLState());
    sqle.printStackTrace();
    while ( (sqle = sqle.getNextException()) != null);
    catch (java.sql.SQLException sqle) {
    do {
    System.out.println(sqle.getMessage());
    System.out.println("Error Code:" +
    sqle.getErrorCode());
    System.out.println("SQL State:" + sqle.getSQLState());
    sqle.printStackTrace();
    while ( (sqle = sqle.getNextException()) != null);
    stmt.clearBatch();
    System.out.println();

  • Running Unix Shell scripts through Java

    How to run Unix shell scripts through Java program ?

    Use:
    Process p = Runtime.getRuntime().exec("sh script.sh");Then you can use:
    p.getOutputStream and read the output of your program.

  • Running a shell script through java

    Hi all,
    I have a simple question here.
    How can I run a shell script through java and put the text output into a string.
    I'd be very grateful if you could show me sample code...
    Have a great day,
    Pesho

    Runtime.exec()
    There are plenty of examples. Read the following before continuing, however, as it will save alot of headaches:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • 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/

  • Running Shell scripts through JAva

    Hi,
    I tried to execute a Shell script through a Java program.
    The code I used is as below:
    import java.lang.*;
    import java.io.*;
    public class sys {
    public static void main(String[] args) {
    Runtime rt = Runtime.getRuntime();
    String[] callAndArgs = { "chgpasswd" };
    try {
    Process child = rt.exec(callAndArgs);
    child.waitFor();
    System.out.println("Process exit code is: " + child.exitValue());
    catch(IOException e) {
    System.err.println( "IOException starting process!");
    catch(InterruptedException e) {
    System.err.println( "Interrupted waiting for process!");
    The "chgpasswd" shell script calls the "passwd" command of Unix.
    It threw out an IO exception.
    Then I gave the parameter as "./chgpasswd". It now gave an exit value of 255.
    The "chgpasswd" script exists in the same directory as the .class file.
    I checkd up the exit code reference...it says exit value of 255 could mean as exit code out of range........an exit code > 255....which unfortunately has no documentation, I guess.
    Can you help ?

    This is on a Unix platform, correct? Assuming so...
    If I remember correctly, exit codes can be greater than 255. To get the real exit code equates to something like: exitcode & 512 to obtain the real exit code.
    Make sure "chgpasswd" shell script has the execute permissions set. Additionally, make sure that the first line of the script (the magic line) has the appropriate shell/interpreter to execute specified. For example, if "chgpasswd" were a Bourne (sh) script, the first like would be:
    #!/bin/shFor perl, it may be something like:
    #!/usr/bin/perlIt needs to be the absolute path to the shell/interpreter is the point.

  • Execute an SQL Script from Java (myScript.sql) ?

    Hello!
    I am a writing an SQL Script so that I can re-create my database on another server (im using my laptop to test it on first though).
    I'm connecting to mySQL server using JDBC which works fine, but I was wondering
    how can I run an entire script file, say myScript.sql from within a Java class??
    (an SQL Script is simply a file containing the regular SQL commands and expressions that you might enter at an sql command line prompt)
    example of an SQL Scritp: myScript.sql>>
    //#create new db
    CREATE DATABASE sample_db;
    //#set active db
    USE sample_db;
    //#set table paramaters
    CREATE TABLE monkeys
    (name CHAR(20),
      age INT UNSIGNED,
      sex ENUM('M','F')
    //#create standard monkeys
    INSERT INTO monkeys(name,age,sex) VALUES("Sammy",10,"M");
    INSERT INTO monkeys(name,age,sex) VALUES("Muncht",12,"M");
    INSERT INTO monkeys(name,age,sex) VALUES("Jill",8,"F");
    //#get recordset
    SELECT * FROM monkeys WHERE age < 50;Thanks for your help!

    The way I understand it is that your mysql.sql script file uses ';' as a delimeter between statements. So now what you can do is that read the whole file and put it inside a string/stringbuffer. Now put this string/stringbuffer to a stringTokenizer with delimeter set as ';'. this way you will recieve your exact statements without scratching your heads as where the statements begin/ends. :-)
    Now once you have your statements than its just a matter of executing them against the database.
    hope this helps.

  • .sql file through Java and procedures

    I want to execute .sql file (on my local system) to run on a oracle database.
    Also please tell me how can I run multiple procedure simultenously through Java class.
    Thanks in Anticipation

    First you need a multi-CPU machine or you're never going to execute more than one statement at once.
    Next you need to know how to create a multithreaded program.
    After that, you need to figure out how to read that file and separate the statements in it so each can be fed to one of those threads.

  • Can't Upload SQL scripts or application scripts in APEX 3.1

    I have installed APEX 3.1 on an Oracle 10g database.
    I can log in to APEX, create applications, and run applications.
    One application I import is the sample OEHR application which imports correctly at the hosted site.
    However, when I try to upload an SQL script or import the sample application I get
    "Page not Found" for this page http://csora:7777/pls/apex/wwv_flow.accept
    I've included my dads.conf below and also some Apache error entries
    Alias /i/ "e:\oracle\product\10.1.0\Db\Apache\Apache\images/"
    AddType text/xml     xbl
    AddType text/x-component     htc
    <Location /pls/apex>
    Order deny,allow
    PlsqlDocumentPath docs
    AllowOverride None
    PlsqlDocumentProcedure      wwv_flow_file_mgr.process_download
    PlsqlDatabaseConnectString     csora:1521:ORCL ServiceNameFormat
    PlsqlNLSLanguage          AMERICAN_AMERICA.AL32UTF8
    PlsqlAuthenticationMode     Basic
    SetHandler          pls_handler
    PlsqlDocumentTablename     wwv_flow_file_object$
    PlsqlDatabaseUsername     APEX_PUBLIC_USER
    plsqlDefaultPage          apex     
    PlsqlDatabasePassword     hocking
    Allow from all
    </Location>
    I:[Mon Apr 14 15:52:35 2008] [error] [client 10.116.101.158] [ecid: 1208202755:198.30.4.195:2696:2864:2873,0] File does not exist: e:/oracle/product/10.1.0/db/apache/apache/htdocs/pls/htmldb/builder/topnav2.gif
    [Mon Apr 14 15:52:35 2008] [error] [client 10.116.101.158] [ecid: 1208202755:198.30.4.195:2696:2924:2771,0] File does not exist: e:/oracle/product/10.1.0/db/apache/apache/htdocs/pls/htmldb/builder/left_curve.gif
    [Mon Apr 14 15:52:35 2008] [error] [client 10.116.101.158] [ecid: 1208202755:198.30.4.195:2696:2944:2767,0] File does not exist: e:/oracle/product/10.1.0/db/apache/apache/htdocs/pls/htmldb/builder/left_curve.gif
    [Mon Apr 14 15:52:35 2008] [error] [client 10.116.101.158] [ecid: 1208202755:198.30.4.195:2696:2972:2750,0] File does not exist: e:/oracle/product/10.1.0/db/apache/apache/htdocs/pls/htmldb/builder/right_curve.gif
    [Mon Apr 14 15:52:35 2008] [error] [client 10.116.101.158] [ecid: 1208202755:198.30.4.195:2696:2940:2762,0] File does not exist: e:/oracle/product/10.1.0/db/apache/apache/htdocs/pls/htmldb/builder/right_curve.gif
    [Mon Apr 14 16:19:33 2008] [error] [client 10.116.101.158] [ecid: 1208204373:198.30.4.195:2696:2924:2773,0] File does not exist: e:/oracle/product/10.1.0/db/apache/apache/htdocs/pls/htmldb/builder/topnav2.gif
    [Mon Apr 14 16:21:48 2008] [error] [client 10.116.101.158] [ecid: 1208204507:198.30.4.195:2696:2948:2801,0] mod_plsql: /pls/apex/wwv_flow.accept HTTP-404 ORA-00942: table or view does not exist
    [Mon Apr 14 16:23:29 2008] [error] [client 10.116.101.158] [ecid: 1208204609:198.30.4.195:2696:2788:2760,0] mod_plsql: /pls/apex/wwv_flow.accept HTTP-404 ORA-00942: table or view does not exist
    [Mon Apr 14 16:23:29 2008] [error] [client 10.116.101.158] [ecid: 1208204609:198.30.4.195:2696:2788:2761,0] mod_wchandshake: incorrect uri: name="p_t04" passed in.
    [Mon Apr 14 16:23:29 2008] [error] [client 10.116.101.158] [ecid: 1208204609:198.30.4.195:2696:2788:2761,0] Invalid URI in request -data; name="p_t04"
    Am I missing some files or directories from the 3.1 install? Any help would be appreciated since I think I'm close to having APEX fully functional.

    Val,
    In this line:
    PlsqlDocumentTablename wwv_flow_file_object$
    ...that needs to be wwv_flow_file_objects$
    Scott

  • How can i execute vb scripts in java program

    hi
    how can i execute any batch files or any other exe files (vb scripts) from java programs
    thanks

    Hi,
    You use Runtime.exec to execute commands / exe-files. See the documentation (and remember that it will only work on windows):
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html
    /Kaj

  • How i can execute the sql query in java code

    I already have sql query in jave plateform i need to execute this code how i can do that. i have unix env and with oracle database. should i just run this query in my sqlplus. this file has extention .java. thanks

    you can create a project in JDeveloper add the java file to it, add the Oracle JDBC library to the project properties and then hit the run button.

  • Can we operate cd roms through java programs

    can any help in this.

    Standard Java treats CD drives just like any other drive in the file system. Beyond that you'd need native code and an extended library package of some sort

  • Can't connect sql server through static ip

    i am using sql server but before installing a fresh window recently i can connect my sql server as my static ip as a server name. but after installation i can't connect .. how can i do so.. 

    Just for clarification, it sounds like you had SQL Server installed on your computer and that you had to reinstall Windows for reason and reinstall SQL Server again, now you are having problems connecting? 
    Can you tell us which services you installed (i.e., Database Engine, Reporting Services, Analysis Services), the version/edition you are working with, and which service is causing you problems?  Also, how are you attempting to connect? From the computer
    its installed on, or remotely from another computer? Which version of Windows are you working with?

  • Run a .sh script through JAVA ?

    Hi All,
    I have a shell script that basically gives me some status on my UNIX box. The name of the script is "scstat". But I need to parse the output shown by this script using JAVA.
    Does anybody know of any code or let me know the ways to implement this......your help is appreciated.
    Best Regards, sangita

    Test with string "ls -al", etc..
    import java.io.DataInputStream;
    import java.io.IOException;
    * Created on Apr 26, 2004
    * To change the template for this generated file go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    * @author root
    * To change the template for this generated type comment go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    public class Execute {
         public static void main(String[] args) {
              Execute ex = new Execute();
              ex.execute("./scstat.sh" );     //if in current directory, need the path.
         /**Returns the output
          * @param string
         public static String execute(String string) {
              Process p;
              String s = null;
              try {
                   p = Runtime.getRuntime().exec(string);
              //     p.waitFor();
              DataInputStream in = new DataInputStream(p.getInputStream());
              while ( (s=in.readLine())  !=  null){
                   System.out.println(s);
              } catch (IOException e) {
                   e.printStackTrace();
              return s;
    }

  • Calling sql script through shell script

    Hi All
    I am trying to run one shell script it will execute the sql file which is in UNIX box. Problem here i am facing is
    when i submit the program through front end it taking time to execute and the status in running even for hours and hours. Manually i am terminating the concurrent program.
    But when same shell script when i tried to execute in putty it generating the output with in seconds
    Can you help what may be the error? I used the syntax like this
    Can you help what may be the error? need to change any syntax
    Thanks
    Prem Raj Dasari
    Edited by: Sravprem on Sep 20, 2012 12:43 AM

    Pl post details of OS, database and EBS versions. In your shell script, insert this line as the first line
    set -xthen run the concurrent program and paste the contents of the log of the concurrent program here
    HTH
    Srini

Maybe you are looking for