Multiple sql statements from java

I am executing sql statements in MaxDB 7.6.04.12 from java using jdbc.
I want to execute multiple statements at a time, but it seems that however I separate the statements, I get
com.sap.dbtech.jdbc.exceptions.DatabaseException: [-3014] (at 433): Invalid end of SQL statement
I have tried separating the statements with just a semi-colon, with a semi-colon and new line, with newline-//-newline (as works with SQL Studio), but whatever I try I get this error or some other.
Is it possible to do this? and if so how?
Thanks
Chris

Hi Lars,
Here are the relevant bits of code.
However I'm not sure how helpful that will be - I'm using the SpringFramework for my jdbc calls, as it saves a lot of time and effort, and my calls are to Spring methods, which are wrappers round the base jdbc calls.
I'll post it anyway, just in case you're familiar with Spring. I haven't looked at the Spring code, but my understanding is it pretty much just passes the sql to standard jdbc calls.
I guess my next step would be to trace through the Spring code as it executes and see if anything becomes apparent. However I'm under some time pressure and was hoping to avoid that.
My other alternative is to create non-temporary tables, and drop them explicitly when I've finished with them.
    public Set<String> getPriceUpdatedProducts() {
        final Set<String> prods = new TreeSet<String>();
        String sql;
        int updates;
        // need single connection template so subsequent statements can access temp tables:
        JdbcTemplate jtSingle = getSingleConTemplate(jdbcTemplate);
        // inDCs is a list of dist channels for an sql 'in' statement:
        String inDCs = "";
        for (String siteId: siteConfig.getAllSiteIds()) {
            if (!"".equals(inDCs)) inDCs += ",";
            inDCs += "'" + siteConfig.getSiteIdProperty(siteId, "distChanId") + "'";
        // Clear all the changed flags from the last run:
        updates = jtSingle.update("update zchangedartdc set changed = '' ");
        // Get the current data into a temp table:
        sql = "create table temp.pricechanges as " +
              "select A304.matnr, A304.vtweg, konp.kbetr price " +
              "  from A304 join konp " +
              "    on A304.knumh = konp.knumh " +
              "   and A304.mandt = konp.mandt " +
              "   and A304.vkorg = '" + salesOrg + "' " +
              "   and A304.vtweg in (" + inDCs + ")" +
              "   and A304.kschl = '" + rrpCondType + "' " +
              "   and A304.mandt = '" + sapClient + "' " +
              "   and konp.kschl = '" + listCondType + "' " +
              "   and char(date, internal) >= chr(A304.datab) " +
              "   and char(date, internal) <= chr(A304.datbi) " +
              "   and A304.kappl = 'V' ";
        jtSingle.execute(sql);
        // Get the changes into a second temp table:
        sql = "create table temp.changedarts as " +
              "select temp.pricechanges.* " +
              "  from temp.pricechanges, zchangedartdc " +
              " where zchangedartdc.matnr = temp.pricechanges.matnr " +
              "   and zchangedartdc.vtweg = temp.pricechanges.vtweg " +
              "   and zchangedartdc.price != temp.pricechanges.price ";
        jtSingle.execute(sql);
        // save the changes, and flag them:
        sql = "update zchangedartdc " +
              "   set (price, changed) = (select price, 'X'  " +
              "                             from temp.changedarts " +
              "                            where zchangedartdc.matnr = temp.changedarts.matnr " +
              "                              and zchangedartdc.vtweg = temp.changedarts.vtweg) " +
              " where matnr||vtweg in (select matnr||vtweg from temp.changedarts) ";
        updates = jtSingle.update(sql);
        // add the new items that weren't there last time, and flag them:
        sql = "insert into zchangedartdc " +
              "select '" + sapClient + "', matnr, vtweg, 'X', price " +
              "  from temp.pricechanges " +
              " where matnr||vtweg not in (select matnr||vtweg from zchangedartdc) ";
        updates = jtSingle.update(sql);
        // now we've got all the changes flagged, we can get the list of changed products:
        jtSingle.query("select distinct matnr from zchangedartdc " +
                       " where changed = 'X' ",
                       new RowCallbackHandler() {
                           public void processRow(ResultSet rs) throws SQLException {
                               prods.add(rs.getString("matnr"));
        // release the connection:
        destroySingleConnection(jtSingle);
        return prods;
     * Return a JdbcTemplate which will always use the same connection. Parameter jt is just
     * a convenient way to get a DataSource from which to get a Connection.
     * When the calling prodedure has finished, it MUST call
     * destroySingleConnection(jt)
     * @param jt
     * @return
    private JdbcTemplate getSingleConTemplate(JdbcTemplate jt) {
        Connection con;
        try {
            con = jt.getDataSource().getConnection();
            con.setAutoCommit(true);
        } catch (SQLException e) {
            throw new DataAccessResourceFailureException("Failed to get Connection for SingleConnectionDataSource", e);
        SingleConnectionDataSource singleDs = new SingleConnectionDataSource(con, true);
        return new JdbcTemplate(singleDs);
    private void destroySingleConnection(JdbcTemplate singleConJt) {
        try{
            ((SingleConnectionDataSource)singleConJt.getDataSource()).destroy();
        } catch (SQLException e) {
            throw new DataAccessResourceFailureException("Failed to destroy SingleConnectionDataSource", e);

Similar Messages

  • How to isolate the Sql Statement from Java Code

    Hi
    I Need to know that can we segregate the Sql Statements and convert them to Stored Procedures so as to isolate the Sql statements from Java Code.
    So i have one static web page which uses four select Statements so what i want is to create a stored procedure encapsulating these queries. So that the Java Web Developer will simply call the Stored Procedure instead of using four different SQL Statements.
    Suppose the developer has these four Statements
    Select ename,empno,sal,job from emp;
    select empno,ename,mgr from emp;
    select deptno,dname from dept;
    select emp.ename,emp.empno,emp.deptno,dept,dname fromemp,dept;
    So can i encapsulate these four Sql Statements in one Procedure and the Web developer can call the Store procedure and dont need to write the Sql Statements in his code.
    Can Anybody guide me how to write this Stored type of Store procedure.
    Thanks

    http://www.google.com/search?q=java+windows+registry
    Next time, search yourself. It might be beyond your belief, but you're really, really not the first person to wonder about this.

  • Executing multiple sql statements from a single sql file

    Hi, I am Vijay Krishna.
    I want to drop user, drop tablespace, create tablespace and create user from a single executable file or a single sql file. The command should be in sequence. How can we achieve it? Can I anybody help me in this regard. I want this as soon as possible. It's urgent. Kindly post a reply.
    Also, how can we know the oracle home directory from a java program? The problem is we should know the Oracle home directory and use it for creating the tablespace. In the userinterface we will give just for a new database user creation. I will be really thankfull if anybody can help me in this regard.

    It is showing any error messages.
    I will diplay the entire batch file which we are using.
    sqlplus / as sysdba
    drop user examination cascade;
    drop tablespace examination;
    create tablespace examination
    datafile 'C:\oracle\product\10.1.0\oradata\orcl\examination.dbf'
    size 500M autoextend on;
    create user examination identified by examination
    default tablespace examination
    quota unlimited on examination;
    grant connect, resource to examination;
    exit;
    when i run the batch file from the DOS prompt it is entering into the sql prompt and coming out in a fraction of a second. We are just seeing a screen coming and going. But no error messages are being displayed.
    first we thought that as we are giving the create tablespace and create user in the same file we created another file and tried without having the create commands. Even then the user didn't get dropped.

  • Running multiple SQL statements from DBMS_SCHEDULER

    DB Version : 10.2.0.4
    After refering the following document, i am trying to create a job which will run 2 SQLs ; An INSERT and an UPDATE as shown below.
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14231/jobtosched.htm#i1018602
    create table xyz (empid  number,empname varchar2(35),cre_dt date);
    BEGIN
    DBMS_SCHEDULER.CREATE_JOB(
       job_name          =>  'job32',
       job_type          =>  'PLSQL_BLOCK',
       job_action        =>  'INSERT INTO XYZ VALUES (7935, ''SALLY'',SYSDATE),'UPDATE MANU.XYZ SET EMPID = 33';
       start_date        =>  SYSDATE,
       repeat_interval   =>  'FREQ = DAILY; INTERVAL = 1');
    END;
    /But i am getting errors like below, when i try to create the above job.
    ORA-01756: quoted string not properly terminated
    PLS-00103: Encountered the symbol ";" when expecting one of the following:

    You need to enclose those statements in an anonymous PL/SQL block
    BEGIN
    DBMS_SCHEDULER.CREATE_JOB(
       job_name          =>  'job32',
       job_type          =>  'PLSQL_BLOCK',
       job_action        =>  'BEGIN INSERT INTO XYZ VALUES (7935, ''SALLY'',SYSDATE); UPDATE MANU.XYZ SET EMPID = 33; END;'
       start_date        =>  SYSDATE,
       repeat_interval   =>  'FREQ = DAILY; INTERVAL = 1');
    END;
    /

  • Multiple SQL statements from JDBC

    Dear All,
    We are working on R/3- >XI->JDBC scenario. We have sender as Proxy which sends some data to XI which needs to be Updated in multiple database tables in oracle. We have few Insert,Update and Delete Query to be

    Hi
    yes this can be done by using the concept IDOC to JDBC
    ALe settings for thi s are :
    Steps for XI
    Step 1)
    Goto SM59.
    Create new RFC destination of type 3(Abap connection).
    Give a suitable name and description.
    Give the Ip address of the R3 system.
    Give the system number.
    Give the gateway host name and gateway service (3300 + system number).
    Go to the logon security tab.
    Give the lang, client, username and password.
    Test connection and remote logon.
    Step 2)
    Goto IDX1.
    Create a new port.
    Give the port name.
    Give the client number for the R3 system.
    Select the created Rfc Destination.
    Step 3)
    Goto IDX2
    Create a new Meta data.
    Give the Idoc type.
    Select the created port.
    Steps for R3.
    Step 1)
    Goto SM59.
    Create new RFC destination of type 3(Abap connection).
    Give a suitable name and description.
    Give the Ip address of the XI system.
    Give the system number.
    Give the gateway host name and gateway service (3300 + system number).
    Go to the logon security tab.
    Give the lang, client, username and password.
    Test connection and remote logon.
    Step 2)
    Goto WE21.
    Create a port under transactional RFC.(R3->XI)
    Designate the RFC destination created in prev step.
    Step 3)
    Goto SALE.
    Basic settings->Logical Systems->Define logical system.
    Create two logical systems(one for XI and the other for R3)
    Basic settings->Logical Systems->Assign logical system.
    Assign the R3 logical system to respective client.
    Step 4)
    Goto WE20.
    Partner type LS.
    Create two partner profile(one for XI the other for R3).
    Give the outbound or inbound message type based on the direction.
    Step 5)
    Not mandatory.
    Goto BD64.
    Click on Create model view.
    Add message type.
    Step 6)
    Goto WE19
    Give the basic type and execute.
    fill in the required fields.
    Goto IDOC->edit control records.
    Give the following values.(Receiver port,partner no.,part type and sender Partner no. and type)
    Click outbound processing.
    Step 7)
    Go to SM58
    if there are any messages then there is some error in execution.
    Goto WE02.
    Check the status of the IDOC.
    Goto WE47.
    TO decode the status code.
    BD87 to check the status of IDOC.
    In case if not authorized then go to the target system and check in SU53, see for the missing object
    and assign it to the user.
    for scenario reffer link
    Configuring JDBC Connector Service To Perform Database Lookups
    http://searchsap.techtarget.com/tip/0,289483,sid21_gci1246926,00.html
    Configuration of JDBC Adapter for SQL Server
    JDBC Driver = com.microsoft.jdbc.sqlserver.SQLServerDriver
    Connection = jdbc:microsoft:sqlserver://hostname:<port>;DatabaseName=<DBName>
    UserID and Password
    Configuring the Receiver JDBC Adapter
    http://help.sap.com/saphelp_nw2004s/helpdata/en/b0/676b3c255b1475e10000000a114084/content.htm
    hope this helps you
    Regard's
    Chetan Ahuja

  • Workspace to parse SQL statements from multiple database schema's

    Hi ,
    When go through the following link of workspace admin user :
    Home>HTML DB Workspace Administration>Manage Services>Schema Reports>Workspace Schemas there I saw "Your workspace has the privilege to parse SQL statements using the following database schemas. Note that the terms database schema and database user can be used interchangeably.
    " at the right pane.
    So how can i make my workspace to parse SQL statements from multiple database schema's ?That must be listed there .But i have only one schema in view ? Can i make it multiple ?If then How ?
    Anybody have an idea ?
    ROSY

    Assign as many schemas to your workspace as you want using the administration app. Read about it in the doc.
    Scott

  • Convert a logic from SQL statement to java

    Hi.,
    I m using jdeveloper 11.1.1.5
    I had used one sql statement as gievn below
    (SELECT max(decode(LENGTH(fy_year),4, fy_year + 1,6,SUBSTR(fy_year, 1, 4)+1||SUBSTR(SUBSTR(fy_year, 1, 4) + 2, 3, 2)))YEAR from fin_years)I need to use this logic in java
    Could anyone pls help me

    "wilhelm,"
    I've seen some ridiculous questions in my life. This is one of them.
    There are just so many things wrong here. So, so many.
    SELECT statements get data from databases; they are not "logic."
    Do you really expect us to parse your SQL and try to guess what it is supposed to do?
    Do you really believe that when converting a Forms app to Java that you "convert" SQL statements to Java?
    Do you really believe that going through your forms app and "converting" it to ADF is a sensible approach?
    John

  • Multiple SQL statements in Init SQL in WLS 8.1

    How to seperate multiple SQL statements in Init SQL text box ?
    For example, I want to enter following two SQL statements. How do I seperate them.
    I tested with / and ; as seperator, but did not worked..
    alter session set nls_date_format = 'MM/DD/YYYY'
    set role xxx_role identified by xxxx

    Mahendra wrote:
    Thanks Joe.
    Following worked for Oracle 8.1.7Good news.
    but did not for 8.0.6
    SQL BEGIN EXECUTE IMMEDIATE 'ALTER SESSION SET nls_date_format = ''MM/DD/YYYY''';
    EXECUTE IMMEDIATE 'SET ROLE xxx identified xxx'; end;
    Do you know 8.0.6 syntax ?You might try asking oracle, but note that no one is supporting that old version
    of Oracle any longer...
    Joe
    >
    Mahendra
    Joe Weinstein <[email protected]> wrote:
    Hi.
    I found the syntax, I think. Try this:
    BEGIN EXECUTE IMMEDIATE 'ALTER SESSION SET nls_date_format = 'MM/DD/YYYY'';
    EXECUTE IMMEDIATE 'SET ROLE <<role name>> identified
    by <<pwd>>';END;
    Joe
    Mahendra wrote:
    Still getting following exception.
    <Feb 19, 2004 1:47:58 PM EST>
    <Warning>
    <JDBC> <BEA-001164>
    <Unable to initialize connection in pool "XXXX".
    Initialization
    SQL = "BEGIN alter session set nls_date_format = 'MM/DD/YYYY'; setrole xxxx_role
    identified by
    xxxx; END;".
    Received exception: "java.sql.SQLException: ORA-06550: line 1,column7:
    PLS-00103: Encountered the symbol "ALTER" when expecting one of thefollowing:
    begin declare exit for goto if loop mod null pragma raise
    return select update while <an identifier>
    <a double-quoted delimited-identifier> <a bind variable> <<
    close current delete fetch lock insert open rollback
    savepoint set sql commit <a single-quoted SQL string>
    The symbol "update was inserted before "ALTER" to continue.
    ORA-06550: line 1, column 61:
    PLS-00103: Encountered the symbol "ROLE" when expecting one of thefollowing:
    transaction
    ".>
    <Feb 19, 2004 1:47:59 PM EST> <Notice> <WebLogicServer> <BEA-000355><Thread "Li
    Joe Weinstein <[email protected]> wrote:
    Mahendra wrote:
    Thanks for reply, but that did not worked.
    Get following exception
    Unable to initialize connection pool "POOL_NAME".
    Initialization SQL = "Select count(*) from ""SQL BEGIN alter sessionset nls_date_format
    = 'MM/DD/YYYY'; set role xxx_role identified by xxxx; END;"". Receivedexception:
    "java.sql.SQLException: ORA-00972: identifier is too long
    Since we have not given SQL before that statement, BEA is treating
    statment "SQL Begin ....." as a table name.
    Then I tried by putting SQL out side quotes, like SQL "Begin .....end;" but the
    same error.
    Is there any way around it ?
    MahendraHi. The full string you should enter into the console when you define
    the
    initSQL parameter is:
    SQL BEGIN alter session set nls_date_format = 'MM/DD/YYYY'; set role
    xxx_role identified by xxxx; END;
    Let me know...
    Joe
    Joe Weinstein <[email protected]> wrote:
    Mahendra wrote:
    How to seperate multiple SQL statements in Init SQL text box ?
    For example, I want to enter following two SQL statements. How do
    I
    seperate them.
    I tested with / and ; as seperator, but did not worked..
    alter session set nls_date_format = 'MM/DD/YYYY'
    set role xxx_role identified by xxxxThis will always be DBMS-specific. If this is for oracle, you can
    try:
    "SQL BEGIN alter session set nls_date_format = 'MM/DD/YYYY'; setrole
    xxx_role identified by xxxx; END;"
    Joe

  • Extracting SQL statement from a Webi document's data provider using SDK.

    Hi all,
    Is it possible to extract the SQL statement from an existing Webi document's data provider using BO SDK?  I've searched through the class library but haven't found any information on this yet.  If you have done it, could you provide some guidance.  Many thanks.

    I found the following Java code that might be of some help to you. I realize you are using .NET but this might push you down the right path.
    The trick here is to use the Report Engine SDK to get the DataProvider of the DocumentInstance. Then, look at the SQLDataProvider to get your SQLContainer.
    My apologies for the poor formatting. This didn't copy and paste over to the forums very well. I've cleaned up as much as I could.
    <%@ page import="com.crystaldecisions.sdk.framework.*" %>
    <%@ page import="com.crystaldecisions.sdk.exception.SDKException" %>
    <%@ page import="com.crystaldecisions.sdk.occa.infostore.*" %>
    <%@ page import="com.businessobjects.rebean.wi.*" %>
    <%
    boolean loginSuccessful = false;
    IEnterpriseSession oEnterpriseSession = null;
    String username = "username";
    String password = "password";
    String cmsname  = "cms_name";
    String authenticationType = "secEnterprise";
    try
    //Log in. oEnterpriseSession = CrystalEnterprise.getSessionMgr().logon( username, password, cmsname, authenticationType);
    if (oEnterpriseSession == null)
    out.print("<FONT COLOR=RED><B>Unable to login.</B></FONT>");
    else
    {  loginSuccessful = true;
    catch (SDKException sdkEx)
    { out.print("<FONT COLOR=RED><B>ERROR ENCOUNTERED</B><BR>" + sdkEx + "</FONT>");}
    if (loginSuccessful) { IInfoObject oInfoObject = null;
    String docname = "WebI document name";
    //Grab the InfoStore from the httpsession IInfoStore oInfoStore = (IInfoStore) oEnterpriseSession.getService("", "InfoStore");  //Query for the report object in the CMS.  See the Developer Reference guide for more information the query language.   String query = "SELECT TOP 1 * " +        "FROM CI_INFOOBJECTS " +        "WHERE SI_INSTANCE = 0 And SI_Kind = 'Webi' " +        "AND SI_NAME='" + docname + "'";
    IInfoObjects oInfoObjects = (IInfoObjects) oInfoStore.query(query);
    if (oInfoObjects.size() > 0)
    //Retrieve the latest instance of the report  oInfoObject = (IInfoObject) oInfoObjects.get(0);
      // Initialize the Report Engine  ReportEngines oReportEngines = (ReportEngines)
    oEnterpriseSession.getService("ReportEngines"); 
    ReportEngine oReportEngine = (ReportEngine) oReportEngines.getService(ReportEngines.ReportEngineType.WI_REPORT_ENGINE);
      // Openning the document  DocumentInstance oDocumentInstance = oReportEngine.openDocument(oInfoObject.getID());   
    DataProvider oDataProvider = null; 
    SQLDataProvider oSQLDataProvider = null; 
    SQLContainer oSQLContainer_root = null; 
    SQLNode oSQLNode = null;
    SQLSelectStatement oSQLSelectStatement = null; 
    String sqlStatement = null;
      out.print("<TABLE BORDER=1>");
    for (int i=0; i<oDocumentInstance.getDataProviders().getCount(); i++)
    oDataProvider = oDocumentInstance.getDataProviders().getItem(i);
      out.print("<TR><TD COLSPAN=2 BGCOLOR=KHAKI>Data Provider Name: " + oDataProvider.getName() + "</TD></TR>");
       if (oDataProvider instanceof SQLDataProvider)
    oSQLDataProvider = (SQLDataProvider) oDataProvider;
        oSQLContainer_root = oSQLDataProvider.getSQLContainer();
        if (oSQLContainer_root != null)
    for (int j=0; j<oSQLContainer_root.getChildCount(); j++)
    oSQLNode = (SQLNode) oSQLContainer_root.getChildAt(j);
          oSQLSelectStatement = (SQLSelectStatement) oSQLNode;             
    sqlStatement = oSQLSelectStatement.getSQL();     
    out.print("<TR><TD>" + (j+1) + "</TD><TD>" + sqlStatement + "</TD></TR>");   
    else
    out.print("<TR><TD COLSPAN=2>Data Provider is not a SQLDataProvider.  SQL Statement can not be retrieved.</TD></TR>");   }  }  out.print("</TABLE>");
      oDocumentInstance.closeDocument(); }
    oEnterpriseSession.logoff();}%>

  • How to store data into database by reading sql statements from text file

    how to write java program for storing data into database by reading sql statements from text file

    Step 1: Create a property file to add various queries.
    Step 2: Read the properties file using ResourceBundle
    Step 3: Use the jdbc to execute the query read from the property file.
    So in future if you need to change query no need do any modifications in java program. But depends on how you use the property file.

  • How Can I Retrieve SQL Statement From The User ?

    Hi
    I want to know, how can I make the user can enter the SQL statement from himself ?? in this code he can't enter it. Only he can display the SQL that i wrote it...
    this is my Code:
    import java.sql.*;
    public class db_testing {
         static final String DRIVER = "com.mysql.jdbc.Driver";            
         static final String DATABASE_URL = "jdbc:mysql://localhost/S204111933";
         public static void main(String[] args) {
              Connection cn=null;
              Statement st= null;
              ResultSet rset=null;
              try{
                   Class.forName(DRIVER);
                   cn=DriverManager.getConnection(DATABASE_URL, "root", "admin");
                   st=cn.createStatement();
                   rset=st.executeQuery("select * from employee");
                   ResultSetMetaData metadata=rset.getMetaData();
                   System.out.println("The begining: ");
                   for(int i=1;i<=metadata.getColumnCount();i++)
                   System.out.print(metadata.getColumnName(i)+"\t");
                   System.out.println();
                   System.out.println();
                   while(rset.next()){
                   for(int i=1;i<=metadata.getColumnCount();i++)
                   System.out.print(rset.getObject(i)+"\t\t");
                   System.out.println();}
              catch(Exception e){
                   e.printStackTrace();
              finally{
                   try{
                   cn.close();
                   st.close();
                   rset.close();
                   catch(Exception e1){
                        e1.printStackTrace();
    }

    The following changes in the code will make the user to give the input
    import java.sql.*;
    public class db_testing {
    static final String DRIVER = "com.mysql.jdbc.Driver";
    static final String DATABASE_URL = "jdbc:mysql://localhost/S204111933";
    public static void main(String[] args) {
    Connection cn=null;
    Statement st= null;
    ResultSet rset=null;
    try{
    Class.forName(DRIVER);
    cn=DriverManager.getConnection(DATABASE_URL, "root", "admin");
    // st=cn.createStatement();
    // rset=st.executeQuery("select * from employee");
    PreparedStatement pstmt=null;
    pstmt=cn.prepareStatement("select * from employee where id=?");
    pstmt.setInt(1,Integer.parseInt(args[0]));
    rset=pstmt.executeQuery();
    ResultSetMetaData metadata=rset.getMetaData();
    System.out.println("The begining: ");
    for(int i=1;i<=metadata.getColumnCount();i++)
    System.out.print(metadata.getColumnName(i)+"\t");
    System.out.println();
    System.out.println();
    while(rset.next()){
    for(int i=1;i<=metadata.getColumnCount();i++)
    System.out.print(rset.getObject(i)+"\t\t");
    System.out.println();}
    catch(Exception e){
    e.printStackTrace();
    finally{
    try{
    cn.close();
    st.close();
    rset.close();
    catch(Exception e1){
    e1.printStackTrace();
    }

  • Error PLS-00306 during calling PL/SQL function from Java

    Hi all,
    I am facing a problem during call of oracle PL/SQL function from java using CallableStatement.
    I receive following error message.
    java.sql.SQLException: ORA-06550: line 1, column 13:
    PLS-00306: wrong number or types of arguments in call to 'EXPORT_HIST_ALARMS_FUNC'
    ORA-06550: line 1, column 7:
    PL/SQL: Statement ignored
    As per above error EXPORT_HIST_ALARMS_FUNC in oracle has this signature.
    CREATE OR REPLACE FUNCTION EXPORT_HIST_ALARMS_FUNC(startDateTime VARCHAR2, endDateTime VARCHAR2, meType VARCHAR2) RETURN VARCHAR2 IS
    END EXPORT_HIST_ALARMS_FUNC;
    Above function I have called following way in java.
    String sql = "begin ?:= EXPORT_HIST_ALARMS_FUNC(?, ?, ?); end;" ;
    CallableStatement cStatement = null;
    cStatement = connection.prepareCall(sql);
    cStatement.registerOutParameter(1,Types.VARCHAR);
    cStatement.setString(2,startDateTime);
    cStatement.setString(3,endDateTime);
    cStatement.setString(4,meType);
    cStatement.execute();
    msg = cStatement.getString(1);
    Actually above function requires three input parameters and one return parameter.
    During execution of above java code it throws SQLException and shows PLS-00306: wrong number or types of arguments in call to 'EXPORT_HIST_ALARMS_FUNC' error.
    I have run this function directly from oracle with three parameters and run successfully and finally it returns string.
    But I am unable to figure out why it doesn't run from above java code.
    Please help regarding this.
    Thanks.
    Regards,
    Shardul Banker

    Try this:
    String sql = "begin ?:= EXPORT_HIST_ALARMS_FUNC(?, ?, ?); end;" ;
    CallableStatement cStatement = null;
    cStatement = connection.prepareCall(sql);
    cStatement.registerOutParameter(1,Types.VARCHAR);
    cStatement.setString(1,startDateTime);
    cStatement.setString(2,endDateTime);
    cStatement.setString(3,meType);
    cStatement.execute();
    msg = cStatement.getString(1);Regards,
    Martijn Teigeler
    Edited by: mTeigeler on Oct 13, 2007 10:22 AM

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

  • Building up dymanic SQL statement from user entered fields on a jsp

    Hi guys.
    I'm building up a sql statement from a bunch of input fields that the users can type in on a .jsp page. No real problem there, but I get a problem when they type in words with ' character in it Eg: Don't, I'll etc.
    This confuses the java code totally and usually results in a spectacular crash of the system.
    Any ideas/thought/wild speculations would be most appreciated.
    Regards
    Elmar Matthee
    University of Stellenbosch
    South Africa

    Even in pure read-only databases SQL injection can be a problem, as the user might be able to read data he should not be able to see.
    You can also create dynamically created sql statements using PreparedStatements, that's not a problem, I'm doing it pretty often myself.
    List<Object> arguments = new ArrayList<Object>();
    StringBuilder sql = new StringBuilder("SELECT foo FROM bar WHERE");
    if (someCondition) {
      sql.append(" foobar = ? ");
      arguments.add(someValue);
      if (someOtherCondition) {
        sql.append(" AND barfoo = ?");
        arguments.add(someOtherValue);
    // later on use setObject() to fill in the parametersObviously you'll have to handle putting the correct ANDs and ORs there, but you probably has solved that already, as it isn't any different if you don't use a PreparedStatement.

  • How to execute multiple sql statements

    hi all
    i am wondering if i can execute multiple sql statements in one shot with >> execute immediate command
    for example:
    i define the variable as X := sql statement
    Y := sql statement
    z := sql statement
    can i do execute immediate (X,Y, Z);
    if yes how ?? and if not any possible alternate
    thanks

    Starting with Ganesh's code
    DECLARE
       l_statement                 VARCHAR2 (2000);
       v_passwd                    VARCHAR2 (200);
       v_username                  VARCHAR2 (200) := 'test';
       v_pwd_key                   VARCHAR2 (200) := 'lwty23';
       v_dblink_name               VARCHAR2 (2000);
       v_dblink_drop               VARCHAR2 (2000);
       v_dblink_create             VARCHAR2 (2000);
       v_dblink_check_connection   VARCHAR2 (2000);
       l_number                    NUMBER;
    BEGIN
       --<<c_instance>>
       FOR c_instance IN (SELECT *
                            FROM v_oracle_instances
                           WHERE environment = 'Developement')
       LOOP
          SELECT encpwd_owner.display_db_encpwd (v_username,
                                                 c_instance.host_name,
                                                 c_instance.instance_name,
                                                 v_pwd_key)
            INTO v_passwd
            FROM DUAL;
          v_dblink_name := c_instance.host_name || '_' || c_instance.instance_name;
          v_dblink_create :=
                ' CREATE DATABASE LINK '
             || v_dblink_name
             || ' CONNECT TO '
             || v_username
             || ' '
             || 'IDENTIFIED BY '
             || v_passwd
             || ' USING'
             || ' ''(DESCRIPTION=
    (ADDRESS=(PROTOCOL=TCP)(HOST= '
             || c_instance.host_name
             || ')(PORT='
             || c_instance.LISTENER_PORT
             || '))(CONNECT_DATA=(SID='
             || c_instance.instance_name
             || ')))''';
          v_dblink_check_connection := 'select 1 from global_name@' || v_dblink_name || '.QCM';    --- Notice this change. I am simply selecting 1. That should be enough to test the database link.
          v_dblink_drop := 'drop database link ' || v_dblink_name || '.QCMTLAF';
          -- l_statement := 'BEGIN ' || v_dblink_create ';' || v_dblink_check_connection ';' || v_dblink_drop '; END ;'
          BEGIN
              EXECUTE IMMEDIATE (v_dblink_create);
              DBMS_OUTPUT.PUT_LINE ('DB Link ' || v_dblink_name || ' Created');
         EXCEPTION
            WHEN others THEN
               dbms_output.put_line( 'Failed to create the database link ' || v_dblink_name  );
               dbms_output.put_line( dbms_utility.format_error_backtrace() );
               INSERT INTO error_table( column_list )
                 VALUES( <<list of values>> );
         END;
          EXECUTE IMMEDIATE (v_dblink_check_connection) INTO l_number;    --- Notice this.
          DBMS_OUTPUT.PUT_LINE ('DB Link ' || v_dblink_name || ' Tested');
          BEGIN
             EXECUTE IMMEDIATE (v_dblink_drop); 
             DBMS_OUTPUT.PUT_LINE ('DB Link ' || v_dblink_name || ' Dropped');
          EXCEPTION
             WHEN others THEN
               dbms_output.put_line( 'Failed to drop the database link ' || v_dblink_name  );
               dbms_output.put_line( dbms_utility.format_error_backtrace() );
               INSERT INTO error_table( column_list )
                 VALUES( <<list of values>> );
         END;
       END LOOP;
    END;But I agree with the point that others have brought up that it really doesn't make sense to create and drop a database link like this.
    Justin

Maybe you are looking for

  • Problems publishing shared review comments in Acrobat 8.0

    I created a shared review in Acrobat 8.0 and posted it to a Sharepoint workspace. A reviewer published comments but I was not able to see them. He double-checked, and he was able to see his comments but I was still unable to see them. He checked agai

  • Trigger problem -- can't insert the same data into audit table

    Sir/Madam, I'm trying to use insert trigger with a 'long raw' datatype data for my audit purpose. Each time, the data of original table can be inserted correctly. While the trigger for audit table in which it contains almost the same data as original

  • WLC 5508 and mobility groups

    Hi, We are using 2 WLC 5508 running 7.0.98.0 sw (AP's are 1142) at our primary site. They are hosting 3 different WLAN/SSID's, one for guest and the other 2 are for corporate access. We have put the WLC's in a mobility group, say "AAAA". Now we have

  • Oracle Apps 11i Localization 11i - Argentina

    Has anyone on here ever implemented Argentina localization for GL/AP? Mostly on the AP side. Our implementation is @ 95% The other 5% is finalizing the VAT withholdings. If you have had the misfortune of actually implementing Argentina localization p

  • Bridge freezes after double clicking

    hi, Bridge cs4 freezes after double clicking on files (psd, ai and so on..) Any ideas? My system is XP 64bit. Regards Peter