Want to execute SQL Queries from Textfile

I have a text file full of a bunch of sql queries, of the format:
select something1, something2
from someplace
select something3, something4
from someplace2
select something5, something6
from someplace3
I want to execute these queries one at a time and then after each one executes, I will do something with the resultset. Question is, how do I pull each query from the text file one at a time and execute? I was doing this by using java.util.Scanner and java.lang.StringBuilder where I would scan one line at a time and then check to see if the line is empty, otherwise I append the line to the StringBuilder. If the line is empty, I process whatever is stored in the StringBuilder. The problem with doing this is that it does not preserve the newline from the text file, so I get queries that look like:
"select something5, something6from someplace3"
which of course are invalid. Does anyone know a better way to build SQL queries / statements from a text file? How do I get the newline or carriage return character?

Just replace newline by space?

Similar Messages

  • 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 use database control to execute sql queries which change at run time

    Hi all,
    I need to execute sql queries using database controls , where the sql changes
    at run time
    based on some condition. For eg. based on the condition , I can add some where
    condition.
    Eg. sql = select id,name from emp where id = ?.
    based on some condition , I can add the following condition .
    and location = ?.
    Have anybody had this kind of situation.
    thanks,
    sathish

    From the perspective of the database control, you've got two options:
    1) use the sql: keyword to do parameter substitution. Your observation
    about {foo} style sbustitution is correct -- this is like using a
    PreparedStatement. To do substitution into the rest of the SQL
    statement, you can use the {sql: foo} substitution syntax which was
    undocumented in GA but is documented in SP2. Then, you can build up
    the filter clause String yourself in a JPF / JWS / etc and pass it into
    the DB control.
    For example:
    * @jc:sql statement="select * from product {sql: filter}"
    public Product[] getProducts(String filter) throws SQLException;
    This will substitute the String filter directly into the statement that
    is executed. The filter string could be null, "", "WHERE ID=12345", etc.
    2) you can use the DatabaseFilter object to build up a set of custom
    sorts and filters and pass that object into the DB control method.
    There have been other posts here about doing this, look for the subject
    "DatabaseFilter example".
    Hope that helps...
    Eddie
    Dan Hayes wrote:
    "Sathish Venkatesan" <[email protected]> wrote:
    Hi Maruthi,
    The parameter substituion , I guess is used like setting the values for
    prepared
    statements.
    What I'm trying to do , is change the sql at run time based on some condition.
    For example ,
    consider the following query :
    select col1,col2 from table t where t.col3 > 1
    At run time , based on some condition , I need to add one more and condition.
    i.e. select col1,col2 from table t where t.col3 > 1 and t.col4 < 10.
    This MAY not address your issue but if you are trying to add "optional" parameters
    you may try including ALL the possible parameters in the SQL but send in null
    for those params that you don't want to filter on in any particular case. Then,
    if you word your query
    as follows:
    select col1, col2 from table t where t.col3 > 1 and (t.col4 = {col4param} or
    {col4param} is null) and (t.col5 = {col5param} or {col5param} is null) ...
    you will get "dynamic" filters. In other words, col4 and col5 will only be
    filtered if you send in non-null parameters for those arguments.
    I have not tried this in a WL Workshop database control but I've used
    this strategy dozens of times in stored procedures or jdbc prepared statements.
    Good luck,
    Dan

  • How to execute sql scripts from Powershell across multiple databases

    Re: How to execute sql scripts from Powershell across multiple databases
    I have an tsql script that I want to run across a list of databases. How is the best way to do this in Powershell? Thanks.

    My example below, using just the SMO and not breaking up the batches, the ExecuteWithResults give the following error when the .sql file contains a GO. My script files are as simple as a DECLARE and then a GO.
    WARNING: SQL Script Failed
    The object of type "Microsoft.PowerShell.Commands.Internal.Format.FormatStartData" is not valid or not in the correct sequence. This is likely caused by a user-specified "format-list" comm
    and which is conflicting with the default formatting.
        + CategoryInfo          : InvalidData: (:) [out-lineoutput], InvalidOperationException
        + FullyQualifiedErrorId : ConsoleLineOutputOutOfSequencePacket,Microsoft.PowerShell.Commands.OutLineOutputCommand
    Also, when executing from the ISE, is there a way to force the ISE to release the files. I am having to close the ISE and reopen my script every time I want to make a testing change to the .sql file.
    [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
    $scriptspath = "C:\temp\psExecuteSQLScripts\scripts"
    $SQLServer = "fidevc10"
    $SQLDB = "Bank03"
    # Create SMO Server Object
    $Server = New-Object ('Microsoft.SQLServer.Management.Smo.Server') $SQLServer
    # Get SMO DB Object
    $db = $Server.Databases[$SQLDB]
    # Load All SQL Scripts in Directory
    $scripts = Get-ChildItem -Path (Join-Path $scriptspath "*") -Include "*.sql" -Recurse
    # Loop through each script and execute
    foreach ($SQLScript in $scripts)
    $fullpath = $SQLScript.FullName
    # Read the Script File into Powershell Memory
    $reader = New-Object System.IO.StreamReader($fullpath)
    $script = $reader.ReadToEnd()
    # Execute SQL
    Write-Host "Executing $SQLScript on $SQLDB...."
    try
    $ds = $db.ExecuteWithResults($script)
    Foreach ($t in $ds.Tables)
    Foreach ($r in $t.Rows)
    Foreach ($c in $t.Columns)
    Write-Host $c.ColumnName "=" $r.Item($c)
    Write-Host "Complete"
    catch [Exception]
    Write-Warning "SQL Script Failed"
    echo $_.Exception|format-list -force
    Write-Host " " -BackgroundColor DarkCyan

  • How to execute sql-queries through shell scripting in linux?

    How to execute sql-queries through shell scripting in linux?

    http://www.oracle.com/technology/pub/articles/saternos_scripting.html
    Two simple examples:
    #!/usr/bin/env bash
    set_orafra () {
       orafra=`echo 'set heading off
       select name from v$recovery_file_dest;
       exit' | sqlplus -s / as sysdba`
    set_orafra
    echo $orafra
    #!/usr/bin/env bash
    export ORACLE_SID=instance_name
    export ORACLE_HOME=/path_to_oracle_home_directory
    export LD_LIBRARY_PATH=$ORACLE_HOME/lib
    export PATH=/$ORACLE_HOME/bin/$PATH
    $ORACLE_HOME/bin/sqlplus -s <<EOF
    connect scott/tiger@my_instance_name
    INSERT INTO table VALUES (sysdate);
    exit
    EOFEdited by: Markus Waldorf on Sep 17, 2010 12:19 AM

  • SQL queries from a Citadel database

    We are retrieving data with third-party package SQL queries from a Citadel database. Certain queries for some object members will not return data, but the SQL search application software returns an "error". An analysis of the error from the SQL end does not find problem on SQL side. I suspect corruption of Citadel database. The link to database is good, as most tags do return a value as expected. 
    This problem occurred at the time of re-location of the database to a replacement computer.  Any ideas on how to fix such a problem?

    Can you give an example of the "bad" SQL statement and a good one?
    Ryan Shi
    National Instruments

  • Extracting SQL Queries from Crystal Reports

    I am trying to find a way or a utility to be able extract SQL queries from Crystal reports into a text file for documentation purposes.  These queries are not in the repository, they were entered into each of the reports when the reports were being built and I can't find a way to extract them.  Any ideas/suggestions?

    Hello,
    CR doesn't have the ability, and I don't recall if this has ever been asked previously. Great suggestion for the Idea Place tab in the up right corner of this page.
    If you find a developer it's quite simple to get:
                // log onto the server and then get the SQL.
                rptClientDoc.DatabaseController.LogonEx("van-w-13-dwilli", "xtreme", "sa", "pw");
                GroupPath gp = new GroupPath();
                string tmp = String.Empty;
                rptClientDoc.RowsetController.GetSQLStatement(gp, out tmp);
                // show the SQL but easy enough to save the SQL text to a file.
                MessageBox.Show(tmp, "Data Source Set and SQL Statement", MessageBoxButtons.OK, MessageBoxIcon.Information);
    Of course you need to open the report first, lots of samples on how to...
    Thank you
    Don

  • How could I extract past executed SQL statement from dictionary ?

    We use oracle11gR2 on win2008R2.
    How could I extract the past executed SQL statement from dictionary ? (Is it possible from V$SQLTEXT or other dictionary table ?)

    IvicaArsov wrote:
    Hi,
    You can find executed SQL in V$SQLAREA view (if it's still in memory). If it does'n't exist and you have AWR enabled you can query DBA_HIST_SQLTEXT table, but remember that the statistic information in AWR tables is filtered (1 out of 10).
    I.Arsov
    As you know when taking snapshot oracle will capture only top sql statements and stored in AWR.
    But can you please link(source) dba_hist_sqltext contain only 1 out of 10 filtered data?. In dba_hist_active_sess_history yes it contain 1 out of 10 sampled data.

  • Want to practice SQL queries, do I need to download SQL editor

    Hi All,
    I have a doubt..
    I want to practice SQL queries. for this, do I need to download SQL editor and Intall or If I download any Oracle version, does it will have SQL editor? please anyone answer my question.

    I'm not sure how is it related to Peoplesoft, but if you installed an Oracle client on your client machine, then you have SQL*Plus or SQL Developer.
    Nicolas.

  • Executing SQL queries in SAP-GUI e.g. select * from but000

    Hallo,
    I am newbie in the SAP world. Is there a way to run select statements from SAP GUI? e.g. I want to know how many rows are returning from a join xyz.
    select count() from tabA and tabB where tabA.id = tabB.id and tabA.Name is not null.*
    Is it possible with SQVI (SQ01)?
    Please help.

    Testcase:
    SQL> create table scott.testit
         ( id number not null,
           value1 varchar2(10) not null )
         tablespace DATA;
    Table created.
    SQL> desc scott.testit;
    Name       Null?    Type
    ID        NOT NULL NUMBER
    VALUE1    NOT NULL VARCHAR2(10)
    SQL> insert into scott.testit (id,value1) values ( 1, 'Hello' );
    1 row created.
    SQL> commit;
    Commit complete.
    SQL> select * from scott.testit;
            ID VALUE1
             1 Hello
    ADD COLUMN, the old fashioned way
    SQL> alter table scott.testit add  ( ADDFIELD1 varchar2(5) );
    Table altered.
    SQL> desc scott.testit;
    Name        Null?    Type
    ID         NOT NULL NUMBER
    VALUE1     NOT NULL VARCHAR2(10)
    ADDFIELD1           VARCHAR2(5)
    SQL> select * from scott.testit where ADDFIELD1 is null;
            ID VALUE1     ADDFI
             1 Hello
    Works as expected
    Try to get NOT NULL and DEFAULT to work
    SQL> alter table scott.testit modify ( ADDFIELD1 NOT NULL );
    alter table scott.testit modify ( ADDFIELD1 NOT NULL )
    ERROR at line 1:
    ORA-02296: cannot enable (SCOTT.) - null values found
    SQL> alter table scott.testit modify  ADDFIELD1 default '000';
    Table altered.
    SQL> alter table scott.testit modify ( ADDFIELD1 NOT NULL );
    alter table scott.testit modify ( ADDFIELD1 NOT NULL )
    ERROR at line 1:
    ORA-02296: cannot enable (SCOTT.) - null values found
    No suprise so far. You would usually need to update all NOT NULL
    values to some values and you would be able to enable the NOT NULL constraint
    allthough this may run for quite a while on big tables.
    Now lets try the new stuff
    SQL> alter table scott.testit drop column ADDFIELD1;
    Table altered.
    SQL> alter table scott.testit ADD ADDFIELD1 varchar2(3) DEFAULT '000' not null;
    Table altered.
    SQL> desc scott.testit
    Name        Null?    Type
    ID         NOT NULL NUMBER
    VALUE1     NOT NULL VARCHAR2(10)
    ADDFIELD1  NOT NULL VARCHAR2(3)     <<<< BING !!!
    SQL> select * from scott.testit;
            ID VALUE1     ADD
             1 Hello      000            <<<< Default '000' is working
    SQL> select * from scott.testit where ADDFIELD1 is NULL;
    no rows selected                     <<<< NOW this might be suprising
    SQL> insert into scott.testit (id,value1,addfield1) values (2,'Bye', '000');
    1 row created.
    SQL> commit;                         <<<< Trying to compare "real" '000' with DEFAULT '000'
    Commit complete.
    SQL> select * from scott.testit;
            ID VALUE1     ADD
             1 Hello      000            <<<< Added with default
             2 Bye        000            <<<< inserted as '000'
    SQL> alter table scott.testit modify ADDFIELD1 default '111';
    Table altered.
    SQL> select * from scott.testit;     <<<< Now it gets exciting
            ID VALUE1     ADD
             1 Hello      000            <<<< WOA... How does this work?
             2 Bye        000
    SQL> set longC 20000 long 20000
    SQL> select dbms_metadata.get_ddl('TABLE','TESTIT','SCOTT') from dual;
    DBMS_METADATA.GET_DDL('TABLE','TESTIT','SCOTT')
    CREATE TABLE "SCOTT"."TESTIT"
    (  "ID" NUMBER NOT NULL ENABLE,
        "VALUE1" VARCHAR2(10) NOT NULL ENABLE,
        "ADDFIELD1" VARCHAR2(3) DEFAULT '111' NOT NULL ENABLE           <<<< No '000' DEFAULT
    ) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
    STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
    PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
    TABLESPACE "DATA"
    SQL>
    Looks like Oracle is at least a whole lot more clever than I expected.
    It must have stored the first Default value somewhere else, as the documentation
    says, that the effective rows will NOT be updated (otherwise it would never work so fast).
    I need to dig into how datablocks are dumped and read.
    Just to finalize this:
    SQL> alter table scott.testit modify ADDFIELD1 NULL;
    Table altered.
    SQL> select * from scott.testit;
            ID VALUE1     ADD
             1 Hello      000
             2 Bye        000
    SQL> select * from scott.testit where addfield1 is null;
    no rows selected
    SQL>
    So the change persists even if you revert the constraint allthough the data
    should not been changed. Surely need to do a datablock dump of this.
    Need to do additional tests with indexes.
    But right now I am running out of time.
    May be someone else likes to join the expedition.
    Volker

  • Executing sql script from file, with multiple queries

    Hello,
    I am trying to load an SQL script from a file, parse the script into separate SQL statements, and execute each of them. The final statement will always be a query, and thus will return a result.
    Three problems arise:
    1. I don't know what TYPE of statement each one is (i.e. whether it is an UPDATE or a QUERY), which seems to be required in order to execute it in java (via executeQuery and executeUpdate).
    2. I am not sure of the best way to execute a series of statements (the Statement object has some "batch" functionality, but I'm not sure if there is a better way, or even of the proper way to use this).
    3. I need to be able to make sure the final statement is a QUERY, and thus will return a ResultSet. Otherwise I need to be able to throw an exception.
    This has been causing me a lot of trouble. Any help would be much appreciated.
    Thanks,
    Kevin

    Hi Kevin,
    Have you got any solution for your mentioned problem????
    I am facing almost the same kind of problem like I have some sql files containg simple sql statements as well as code for writting Procs , triggeres, index...functions..and so on. I need to execute this XYZ.sql file from Java side.
    Can you guide me about my problem?????
    Thanks in advance.............
    Mak

  • How to execute SQL queris in BPEL using JDeveloper?????..Please suggest

    Hi,
    I am very new to JDeveloper. Curently i am tryin to execute an SQL query from the BPEL process, there is an query in the source field and the output of the query is to be mapped to a variable field in the target xsd file. the query is fairly simple, like
    SELECT emp
    FROM emp_table
    WHERE emp_id=123
    The target field, namely "employee", is an element from the xsd file. I tried using Java embedding activity to connect to the db and execute the query through a piece of Java code, but couldn't find a way to assign the output of the query to the associated target field. however lately i also discovered the Database Adapter services which helps me to create a database connection, but still i am not sure as of how to handle and map the output of the query to the variable field. Is there any other way to execute database queries in Jdeveloper using BPEL process????????? Please suggest.
    Can somebody please help me in resolving the issue either through Java Embed activity or Database Adapter services??
    Thanks in advance
    Prabha

    http://download.oracle.com/docs/cd/B31017_01/integrate.1013/b28994/adptr_db.htm
    maybe this one is helpful for you.
    best is to use the db adapter for this.
    if you just execute it you will see the format of the output in your audittrial (so some kind of list of employees). In bpel when you doubleclick the invoke-activity you will see the outputvariable.
    With use of xpath you coud loop over this 'list' (collection/array/etc) of employees and do with it whatever you want.
    Too see how you need to loop over the array you could check this :
    http://clemensblog.blogspot.com/2006/03/bpel-looping-over-arrays-collections.html

  • How to execute SQL Query from the Crystal report X1

    Dear All,
    I am using crystal report X1. In my application am creating run time MS Access tables and giving table name at run time based on my requirement . From these tables I want to fetch data based on some condition and to display using crystal report X1. I have never used the SQL Queries in the Crystal reports. Please help me out.
    Thanks and Regards,
    Rahaneef T

    Please note;
    This forum is dedicated to all other development-related questions which are not directly addressed by other forums. This includes Business Objects SDKs, products, or technologies which do not fall under BusinessObjects Enterprise, BusinessObjects Edge, Crystal Reports Server, or Crystal Reports (for example Desktop Intelligence SDK, Universe Designer SDK, Portal Integration Kits, Java User Function Libraries, and other third party technologies or development languages).
    This looks more like a Crystal Reports design issue?
    Ludek

  • I want the list sql queries performed someone in one session based

    V$SESSION V$SQLTEXT and audsid (taken from sys_context('USERENV','SESSIONID') ) are great .. session_id be generated by a trigger when the application logs on) but then uploading the list of sql queries made by that user (application) until they log off seems impossible.
    I've tried creating triggers that check if V$SESSION changes with respect to an audsid number and sql_hash_value but it didn't work. I'm trying to work out why.
    In the meantime I thought I'd post this to see if anyone else foudn another way.
    I don't want to use sql trace that just gives load of info, I just want simple sql queries.
    Auditting seemed a bit complicated, can that list ALL DML and DDL commands made by a user? if so how?
    thanks
    Bobby

    quite right.
    Oracle enterprise dedicated server 9.2.0.8 on solaris 10.
    I just want to log all command DML and DDL, without stats or anything like that, simply a list, in a chronological order would be nice.
    I found something called dbms_fga package but not sure if thats what I want. Seems I have to implement it on specific tables. which is not good if the application hasn't created the tables yet.
    Thanks in advance.

  • BSP Application connection to SQL Express DB to execute SQL Queries

    Hi There everyone,
    I am not sure if I am posting this discussion in the correct section, but please try and help me out.
    I have been tasked to write a BSP Application in the ABAP Workbench.  The purpose of this application is to enable our Weighbridge operators to execute pre-defined SQL Queries by selecting certain criteria from the Application.  The application is based on an HTML frontend which includes the Web Form (Input Fields, Submit buttons).  We have 6 Weighbridges, each has its own HTML page in this application.
    What I need to achieve is the following;
    I need to know how I must setup the connection between the BSP Application and the SQL Express DB.  Each Weighbridge has its own dedicated SQL Express instance + DB.  These SQL Instances are not on the same host as where the BSP Application is located, I think the correct term is "External SQL Instances".  Everything is on the same domain though.
    What code would I need to add to the "OnInitialize" section in the BSP Application, to be able to establish the connection to the SQL Express database using Windows Authentication?
    And what code would I need to attach to my submit buttons in the "OnInputProcessing" in the BSP Application, to execute a SQL Query to that DB and display the results in .CSV format back to the user?
    I have attached 2 screenshots of what the BSP Application interface looks like.  (This is what the user sees)
    I am very new to creating BSP's, and I have never had to link to SQL from HTML / PHP before, so I basically have no knowledge of this.
    Any help will be greatly appreciated.

    Sorry for the late reply.
    Yes, database is always available and online, not involved in Log Shipping or other things.
    At the time of the connection failure I can find the following in the log of the application:
    ProcessID:2452 ,ThreadID:4768 : NI-I - 24/08/2012-15:12:20 - \PCV/src/ni/src/pcvnireceive.cpp - 4741 - Thread 4768 - Receive Thread Started for Remote Node 043SBTMS10DRSP: In Thread index 1:
    ProcessID:2452 ,ThreadID:4768 : NI-I - 24/08/2012-15:12:40 - \PCV/src/ni/src/pcvnireceive.cpp - 4968 - Thread 4768 - Receive Thread Ended for Remote Node 043SBTMS10DRSP: In Thread index 1:
    ProcessID:2452 ,ThreadID:4768 : NI-I - 24/08/2012-15:12:40 - \PCV/src/ni/src/pcvnireceive.cpp - 115 - Thread 4768 - Merge Memory Usage: KB Allocated = 2186, KB in use = 889
    ProcessID:2452 ,ThreadID:1408 : NiJ - E - 25/08/2012-19:35:29 - \PCV/src/ni/src/pcvnijournal.cpp - 2842 - PcvNiJournal::isRetrievePending() - DB Exception.Error: TCP Provider: The specified network name is no longer available.
    Communication link failureQuery timeout expired - State:08S01,Native:64,Origin:[Microsoft][SQL Server Native Client 10.0] State:08S01,Native:64,Origin:Microsoft][SQL Server Native Client 10.0]
    State:S1T00,Native:0,Origin:[Microsoft][SQL Server Native Client 10.0]

Maybe you are looking for