Print SQL Statement

Post Author: Fedor
CA Forum: Data Connectivity and SQL
Somebody knows, how can I print the currently SQL statement?

Post Author: V361
CA Forum: Data Connectivity and SQL
Go to database, Show SQL Query, highlight the query, RIght Click and select copy, then you can paste that into word, or excel, or text file.  An example is pasted below.
SELECT `Customer`.`Region`, `Customer`.`City`, `Customer`.`Address2`, `Customer`.`Address1`, `Customer`.`Customer Name`, `Customer`.`Postal Code`, `Customer`.`Country` FROM   `Customer` `Customer`

Similar Messages

  • Pretty printing SQL statements in Java

    Hello,
    Environment: Oracle 10g (no prepared statements) and WebLogic 10 using WL's connection pooling.
    We have dynamically generated SQL in our Java code and currently print the SQL to our (log4j) logger as one long Java String. Does Oracle offer a method call to better format the SQL prior to calling the logger to log the SQL?
    Thanks,
    Jim

    Hi Jim,
    Just an idea. Oracle SQLDeveloper has a formatting utillity. Since the IDE is written in Java, there just might be a jar/class that can be used elsewhere.
    As said, just an idea. Maybe you can download it and try to investigate yourself.
    Best regards
    Peter

  • Print out sql statement

    Is there any way to print out a sql statement to a window when using on session?
    I have a sql select statement which looks like the following:
    SQL SELECT * FROM table_name
    WHERE column_a = :Value1
    ON SESSION lDBSession;
    I would like to be able to pring out the statement that was actually executed.
    Does anyone have any ideas how this can be done without rewriting the sql?
    Thanks,
    KRC

    Try trace flags
    trc:db:2:1 prints all the sql statements processed by the database session
    trc:db:2:50 shows input values for the sql statement
    On the DB Sessiob.

  • DIsabling printing of the sql statement in command prompt

    Hi.
    I am connecting to an access database with my java application. Problem is, it prints the connection and the sql statement there. Is there any way to disable it?
    Example of what is seen at my command prompt:
    connection is dbc:odbc:Inventory System
    DB: SELECT * FROM Products WHERE ProductID = 1;

    Ah i see where my mistake is now...Gracefully put. Many of the regulars here and in other forums get a little frustrated, either seeing the same basic problems over and over (it's as if Google doesn't work in vast parts of the world) or or the occaisional person who really isn't willing to work or willing to learn - they want "the answer". Sometimes after a bad run of that we get a little sensitive and snarky. Don't feel bad, there's a mountain to learn with JDBC and, personally, I think everyone is entitled to one brain f*rt a week (<snark> although this may count as one-and-a-half </snark>). Good luck.

  • 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();}%>

  • Odd results from SQL statement in JSP

    Hi.
    Getting very strange results from my SQL statement housed in my JSP.
    the last part of it is like so:
    "SELECT DISTINCT AID, ACTIVE, REQUESTOR_NAME, ..." +
    "REQUESTOR_EMAIL" +
    " FROM CHANGE_CONTROL_ADMIN a INNER JOIN CHANGE_CONTROL_USER b " +
    "ON a.CHANGE_CTRL_ID = b.CHANGE_CTRL_ID " +
      " WHERE UPPER(REQUESTOR_NAME) LIKE ? ";   I've set the following variables and statements:
    String reqName = request.getParameter("requestor_name");
    PreparedStatement prepstmt = connection.prepareStatement(preparedQuery);
    prepstmt.setString(1, "%" + reqName.trim().toUpperCase() + "%");
    ResultSet rslts = prepstmt.executeQuery();
    rslts.next();
    int aidn = rslts.getInt(1);          
    int actbox = rslts.getInt(2);     String reqname = rslts.getString(3).toUpperCase();
    String reqemails = rslts.getString(4);
    String bizct = rslts.getString(5);
    String dept = rslts.getString(6);
    String loc = rslts.getString(7);
    Date datereq = rslts.getDate(8);
    String busvp = rslts.getString(9);
    AND SO ONSo then I loop it, or try to with the following:
    <%
      try {
      while ((rslts).next()) { %>
      <tr class="style17">
        <td><%=reqname%></td><td><%=reqemails %></td><td><%=bizct %></td>td><%=dept %></td>
       <td><%=aidn %></td>
      </tr>
      <%
    rslts.close();
    selstmt.close();
    catch(Exception ex){
         ex.printStackTrace();
         log("Exception", ex);
    %>AND so on, setting 13 getXXX methods of the 16 cols in the SQL statement.
    Trouble is I'm getting wildly inconsistent results.
    For example, typing 'H' (w/o quotes) will spit out 20 duplicate records of a guy named Herman, with the rest of his corresponding info correct, just repeated for some reason.
    Typing in 'He' will bring back the record twice (2 rows of the complete result set being queried).
    However, typing in 'Her' returns nothing. I could type in 'ell' (last 3 letters of his name, Winchell) and it will again return two duplicate records, but typing in 'hell' would return nothing.
    Am I omitting something crucial from the while statement that's needed to accurately print out the results set without duplicating it and that will ensure returning it?
    There's also records in the DB that I know are there but aren't being returned. Different names (i.e. Jennifer, Jesse, Jeremy) won't be returned by typing in partial name strings like Je.
    Any insight would be largely appreciated.
    One sidenote: I can go to SQL Plus and accurately return a results set through the above query. Having said that, is it possible the JDBC driver has some kind of issue?
    Message was edited by:
    bpropes20
    Message was edited by:
    bpropes20

    Am I omitting something crucial from the while
    statement that's needed to accurately print out the
    results set without duplicating it and that will
    ensure returning it?Yes.
    In this code, nothing ever changes the value of reqname or any of the other variables.
      while ((rslts).next()) { %>
      <tr class="style17">
        <td><%=reqname%></td><td><%=reqemails %></td><td><%=bizct %></td>td><%=dept %></td>
       <td><%=aidn %></td>
      </tr>
      <%
    } You code needs to be like this:while (rslts.next()) {
      reqname = rslts.getString(3).toUpperCase();
      reqemails = rslts.getString(4);
      bizct = rslts.getString(5);
      dept = rslts.getString(6);
      loc = rslts.getString(7);
      datereq = rslts.getDate(8);
      busvp = rslts.getString(9);
    %>
      <tr class="style17">
        <td><%=reqname%></td><td><%=reqemails %></td><td><%=bizct %></td>td><%=dept %></td>
       <td><%=aidn %></td>
      </tr>
      <%
    There's also records in the DB that I know are there
    but aren't being returned. Different names (i.e.
    Jennifer, Jesse, Jeremy) won't be returned by typing
    in partial name strings like Je.Well, you're half-right, your loop won't display all the rows in the result set, because you call rslts.next(); once immediately after executing the query. That advance the result set to the first row; when the loop is entered, it starts displaying at the 2nd row (or later if there are more next() calls in the code you omitted).

  • Passing parameter into SQL statement in Crystal Reports

    Hi all,
    I would like to call Crystal Reports in JSP. I can handle it well now. But I hope to let user input their selection criteria before printing out the report. I know how to get the parameter value in JSP, but I really dunno how to pass these parameter values into the SQL statement in Crystal Report. Actually, is it possible to do so?
    If anyone has idea, please tell me. Thx Thx!
    Regards,
    Betty

    Dear Sir,
    I want to use Crystal Report as a web base using JSP. But, I am getting how to call .rpt file in .jsp file & passing of parameter.
    If you have any idea, please reply as early as possible
    Thanking U.
    My userid = [email protected]
    Regds
    Pankaj..

  • SQL statement in servlet giving error

    Please let me know if I need to post this on a different forum, but I thought it was applicable to here.
    First, let me preface this post by saying I've inserted hardcoded values at the DB (Oracle) level and it worked just fine, so most of the statement is sound. All the values inserted properly when testing it that way. Also, I've printed the SQL statement to the console and all looks ok there, too.
    Out of this, I'm getting an error citing the following:
    java.lang.ArrayIndexOutOfBoundsException
    also occasionally getting the following error:
    java.sql.SQLException: [Microsoft][ODBC Driver Manager] Invalid cursor state
    In my servlet, I'm attempting the following:
    prior to the insert statement, I'm retrieving the last row number to start the increment from as in:
    Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
    ResultSet rst = stmt.executeQuery("select CHANGE_CTRL_ID from CHANGE_CONTROL_USER order by CHANGE_CTRL_ID");
         rst.last();
         int lastRowNum = Integer.valueOf(rst.getString("CHANGE_CTRL_ID")).intValue();
         rst.close();
         stmt.close();
    ------------ then ------------------------------------------------
    String preparedQuery = "INSERT ALL " +
    "INTO CHANGE_CONTROL_USER " +
    "(CHANGE_CTRL_ID,REQUESTOR_NAME,REQUESTOR_EMAIL,BUS_CONTACT,DEPT,LOCATION,PHONE_NUM,DATE_REQ," +
    "BUSVP,VP_PHONE,VP_DATE,BRANCH,PRIORITY,OPS_MAN_CHG,OPS_MAN_PPCHAP,TRAIN_REQ," +
    "EXIST_SYS_FLD_CHG,BUS_RULES_CHG,NEW_CODING,NEW_BUS_RULE,NEW_SYS_FIELD,REQ_TYPE_OTHER,REQ_OTHER_SPECIFY,IMPACT_RE_COLL," +
    "IMPACT_DEF_LM,IMPACT_DEF_REC_NRE,IMPACT_AUDIT,IMPACT_PERS_COLL,IMPACT_DEF_FCL,IMPACT_BUS_TECH,IMPACT_LEGAL,IMPACT_PRIV_COLL," +
    "IMPACT_DEF_BKRUP_RE,IMPACT_DEC_SUPT,IMPACT_RISK_MGT,IMPACT_DEF_REO,IMPACT_DEF_BKRUP_NRE,IMPACT_QUALSVCS,IMPACT_INTERNAL_CTRL,IMPACT_DEF_WKFL," +
    "IMPACT_DEF_WKOUT,IMPACT_TRAIN_TPI,IMPACT_OTHER,IMPACT_DEF_MGT,IMPACT_DEF_TAX,IMPACT_VEND_MGT,IMPACT_DEF_CTRL,IMPACT_DEF_REC_RE," +
    "IMPACT_BUS_ADMIN,IMPACT_OTHER_SPECIFY,CHANGE_IN_KPMG,CHANGE_IN_OTS,CHANGE_IN_NFR,CHANGE_IN_ARR,CHANGE_IN_BRR, CHANGE_IN_PROC_IMP," +
    "CHANGE_IN_INT_CITI_POL,CHANGE_IN_OTHER,CHANGE_IN_OTHER_SPECIFY, CHANGE_INIT_DETAILS,REQ_INFO_DESCRIPT,REQ_INFO_EXPLAIN_CURRBUS,REQ_INFO_EXPLAIN_PROPOSED,REQ_BEN_PROP_BENEFIT,REQ_BEN_FIN_IMPLEMENT," +
    "REQ_BEN_OPS_IMPLEMENT,YES_FORM,VULN_ASSESS, CBA_CHG, RISK_ACCEPT,MARSITEM, GCCRFP, APP_COMPL_QUES,CAP_EXPEND)" +
    " VALUES (changecontrol_user_seq.nextval,?,?,?,?,?,?,to_date(?,'YYYY-MON-DD HH:MI:SS'),?,?,to_date(?,'YYYY-MON-DD HH:MI:SS'),?,?," + "?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,"
    + "?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
    + "INTO CHANGE_CONTROL_ADMIN "
    + "(AID,CHANGE_CTRL_ID,ADMNAME,CLOSEDATE,ACTIVE)"
    + "VALUES (changecontrol_admin_seq.nextval, changecontrol_user_seq.currval,NULL, NULL, -1)"
    + "SELECT object_name AS REQUESTOR_NAME FROM all_objects where rownum <= 1;";     
    also I've declared all the respective strings for the PreparedQuery statement.
    If you need to see those, here they are:
    PreparedStatement pstmt = connection.prepareStatement(preparedQuery);
                   // stmt = connection.stmt("INSERT INTO RMIS_USER VALUES (?,?,?,?,to_date(?,'YYYY-MON-DD HH:MI:SS'),?,?,?,?,to_date(?,'YYYY-MM-DD HH:MI:SS')");
              pstmt.setInt(1,++lastRowNum);
              pstmt.setString(2,reqName);
              pstmt.setString(3,reqemail);
              pstmt.setString(4,buscont);
              pstmt.setString(5,reqDept);
              pstmt.setString(6,reqLocale);
              pstmt.setString(7,phone_num);
              pstmt.setDate(8,dtreq);
              //pstmt.setCalendar(8,rtnow);
              pstmt.setString(9,busvp_email);
              pstmt.setString(10,vpphone);
              pstmt.setDate(11,dt);
              pstmt.setString(12,branch);
              pstmt.setString(13,priority);
              pstmt.setString(14,opsmanchg);
              pstmt.setString(15,opsmanppchap);
              pstmt.setString(16,train_req);
              pstmt.setString(17,reqexist_sys_fld_chg);
              pstmt.setString(18,reqbus_rules_chg);
              pstmt.setString(19,reqnew_coding);
              pstmt.setString(20,reqnewbus_rule );
              pstmt.setString(21,reqnew_sys_fld);
              pstmt.setString(22,reqother);
              pstmt.setString(23,req_other_specify);
              pstmt.setString(24,imp_recoll);
              pstmt.setString(25,imp_deflm);
              pstmt.setString(26,imp_defrecnre);
              pstmt.setString(27,imp_audit);
              pstmt.setString(28,imppers_coll);
              pstmt.setString(29,imp_deffcl);
              pstmt.setString(30,imp_bustech);
              pstmt.setString(31,imp_legal);
              pstmt.setString(32,imp_privcoll);
              pstmt.setString(33,imp_defbkre);
              pstmt.setString(34,imp_decsupt);
              pstmt.setString(35,imp_riskmgt);
              pstmt.setString(36,imp_defreo);
              pstmt.setString(37,imp_defbknre);
              pstmt.setString(38,imp_qualsvc);
              pstmt.setString(39,imp_intlctrl);
              pstmt.setString(40,imp_defwkfl);
              pstmt.setString(41,imp_defwkout);
              pstmt.setString(42,imp_trtpi);
              pstmt.setString(43,impact_other);
              pstmt.setString(44,imp_defmgt);
              pstmt.setString(45,imp_deftax);
              pstmt.setString(46,imp_vendmgt);
              pstmt.setString(47,imp_defctrl);
              pstmt.setString(48,imp_defrecre);
              pstmt.setString(49,imp_busadm);
              pstmt.setString(50,impact_other_specify);
              pstmt.setString(51,change_in_kpmg);
              pstmt.setString(52,change_in_ots);
              pstmt.setString(53,change_in_nfr);
              pstmt.setString(54,change_in_arr);
              pstmt.setString(55,change_in_brr);
              pstmt.setString(56,change_in_proc_imp);
              pstmt.setString(57,change_inter_citpol);
              pstmt.setString(58,change_in_other);
              pstmt.setString(59,change_in_other_specify);
              pstmt.setString(60,change_init_details);
              pstmt.setString(61,req_info_descript);
              pstmt.setString(62,req_info_explain_currbus);
              pstmt.setString63,req_info_explain_proposed);
              pstmt.setString(64,req_ben_prop_benefit);
              pstmt.setString(65,req_ben_fin_implement);
              pstmt.setString(66,req_ben_ops_implement);
              pstmt.setString(67,projyes);
              pstmt.setString(68,vulnass);
              pstmt.setString(69,cbachg);
              pstmt.setString(70,riskacc);
              pstmt.setString(71,marsitem);
              pstmt.setString(72,gccrfp);
              pstmt.setString(73,applcomp);
              pstmt.setString(74,capexpend);
              pstmt.executeUpdate();
    if anyone sees anything flawed here, please let me know!
    Thanks!
    Message was edited by:
    bpropes20
    Message was edited by:
    bpropes20
    Message was edited by:
    bpropes20

    What a mess. First off, the line pstmt.setInt(1,++lastRowNum); just needs to go away. You're already using a sequence to set the value for the primary keys, you don't need to add a mistake like this.
    I then count 73 question marks (you can verify, I'm not counting again.) That would mean that your indices are off by one, and the ArrayIndexOutOfBounds is probably coming from pstmt.setString(74,capexpend); Dump the ++lastRowNum line, change all of your indices (after verifying the bind count!) and try it again.
    You can see an inherent weakness in the PreparedStatement clauses - one change means manually rewriting all of the indices. A solution is dumping all of your bind values into a List, then loop through the list to do your setXXX statements. If all binds are not of the same type, you can bind the values to some object that identifies type and use those objects in the list instead of the values. A little more complex, but easier to maintain in my opinion.

  • ORA-04044 Error in SQL statement

    Hi All,
    I faced ORA-04044 in a SQL statement being written inside a shell script. I really don't know what is wrong with the script. Without shell variables is working ...
    Here is the excerpt:
    line=`sar -u 2 5 |tail -1`
    var_io=`echo "$line" | awk '{print $6}'`
    var_sys=`echo "$line" | awk '{print $5}'`
    var_user=`echo "$line" | awk '{print $3}'`
    var_idle=`echo "$line" | awk '{print $7}'`
    sqlplus $ora_access <<EOF
    select sysdate, a.hostid, a.inst_num, b.count1, c.count2, $var_user,$var_sys,$var_idle,$var_io
    from dual ,
    (select HOST_NAME hostid, INSTANCE_NUMBER inst_num from v$instance ) a,
    (select count(sid) count1 from v$session where username is not null) b,
    (select count(*) count2 from apps.fnd_concurrent_requests where phase_code ='R') c;
    EOF
    [b]Error Message:
    SQL*Plus: Release 10.2.0.2.0 - Production on Thu Apr 10 02:20:53 2008
    Copyright (c) 1982, 2005, Oracle. All Rights Reserved.
    Connected to:
    Oracle Database 10g Enterprise Edition Release 10.2.0.2.0 - Production
    With the Partitioning, OLAP and Data Mining options
    SQL> 2 3 4 5 (select count(sid) count1 from v where username is not null) b,
    ERROR at line 4:
    ORA-04044: procedure, function, package, or type is not allowed here

    Thanks a lot for instant reply. It worked!!
    I forgot to use the escape character, but the error
    message was not revealing anything :-(If you look carefully you could have spotted it:
    SQL> 2 3 4 5 (select count(sid) count1 from[b] v where username is not null) b,

  • 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();
    }

  • Where to do the abap sql statement in sapscript (PO)

    Hi, all.
    Hope anybody can guide me to find a solution.
    My situation now is i have to do a purchase order in SAPSCRIPT starting from a standard po. I already found out all the related details as below:
    Program           SAPFM06P
    FORM routine      ENTRY_NEU
    Form              MEDRUCK
    So, now the problem now is I have to add some more data on my print out PO. After figure out for some time, I don't know where to do my abap sql statement. Like example, I want to retriece some data from the ADRC table. I opened the standard program SAPFM06P to add in the some sql statement, but i dun know where should i add in. Bcz if we straight away put the related ADRC field in our sapscript, it is useless, right?
    Thanks in advance.

    Thanks a lot.
    So, how should i add in code in order to fetch the data frm ADRC by using that routine. Because i only the codes like below. I don't where should i start add in.
    Form entry_neu using ent_retco ent_screen.
      data: l_druvo like t166k-druvo,
            l_nast  like nast,
            l_from_memory,
            l_doc   type meein_purchase_doc_print.
      clear ent_retco.
      if nast-aende eq space.
        l_druvo = '1'.
      else.
        l_druvo = '2'.
      endif.
      call function 'ME_READ_PO_FOR_PRINTING'
           exporting
                ix_nast        = nast
                ix_screen      = ent_screen
           importing
                ex_retco       = ent_retco
                ex_nast        = l_nast
                doc            = l_doc
           changing
                cx_druvo       = l_druvo
                cx_from_memory = l_from_memory.
      check ent_retco eq 0.
      call function 'ME_PRINT_PO'
           exporting
                ix_nast        = l_nast
                ix_druvo       = l_druvo
                doc            = l_doc
                ix_screen      = ent_screen
                ix_from_memory = l_from_memory
                ix_toa_dara    = toa_dara
                ix_arc_params  = arc_params
                ix_fonam       = tnapr-fonam          "HW 214570
           importing
                ex_retco       = ent_retco.
    endform.
    Or i come wrong place to add in any coding. Plz guide me.
    Thanks in advance.

  • How to get the real SQL statement from a preparedstatement?

    Hi,
    I am trying to log the actual SQL sent to database by the preparedStatement. Since the original SQL I used to prepare the statement has a lot of "?" in it, after setting all the parameters in the preparedStatement, I want to get the final SQL statement executed. Is there a way to get it? Probably the SQL will depend on different drivers.
    Thanks in advance.

    Thanks, changhsu. I tried the tracing technique. But it only prints out the original SQL statement sent to the preparedStatement. The following is part of the log file:
    ======================================================================
    --------NetDirect JSQLConnect Version:2.2708--------
    2002-04-10 14:23:54.818 (1) Connection attempt number 1 Connection ID:1 for host:perseus
    2002-04-10 14:23:55.429 (1) JSQLConnect(2.2708) Trial license - expires on:Thu Apr 25 17:47:32 CDT 2002, unlimited connections
    2002-04-10 14:23:55.449 (2) Connection allocated from pool ID:2
    2002-04-10 14:23:55.72 (2) [Thread[Thread-6,5,main], IO:88cb4, Dbc:1346]] SELECT SHARED_DRIVES FROM EPM_PREFS WHERE PRODUCT='PE'
    2002-04-10 14:23:57.913 (2) Connection closed and returned to connection pool ID:2
    2002-04-10 14:23:58.193 (3) Connection attempt number 2 Connection ID:3 for host:perseus database:epm20 SQL6.5:false
    2002-04-10 14:23:58.203 (3) [Thread[Thread-6,5,main], IO:88cb3, Dbc:1347]] use epm20 set quoted_identifier,ansi_null_dflt_on,ansi_padding on set textsize 2147483647 set transaction isolation level read committed set implicit_transactions off
    2002-04-10 14:24:00.356 (4) Connection allocated from pool ID:4
    2002-04-10 14:24:01.168 (4) [Not Loged In@localhost, IO:88cb2, Dbc:1347]] PreparedStatement::prepare stmt:SELECT PASSWD FROM RESOURCE_INFO WHERE USER_ID=? AND DELETE_FLG IS NULL
    2002-04-10 14:24:01.448 (4) [Not Loged In@localhost, IO:88cb2, Dbc:1347]] RPC:sp_prepare
    2002-04-10 14:24:01.488 (4) [Not Loged In@localhost, IO:88cb2, Dbc:1347]] RPC:sp_execute
    =======================================================================
    I did not try to trace in SQL Server 7. I will have to find out how to do that first.
    Thanks again.

  • Prepared SQL statement to test existence of a value in a row

    Excuse my ignorance in SQL. I didn't do much in SQL queries or DB design in general, but I'm eager to learn.
    Idea behind: I'm traversing a directory tree (Java, jdbc) (depth first) and want to collect all files
    in that tree and put the as BLOBS into the database.
    To find out whether a file is the same as another file (possibly in a different path) I calculate the md5sum
    (not sure whether it is proof against collisions or if I should use SHA-256 or some combination of md5sum + chksum).
    Anyway, let the md5sum be the unique value that makes the identity of a file for now.
    My problem: Find the jdbc/SQL statements that let me decide whether the file (md5sum) is already stored in a ROW
    upon which I can decide to either do the INSERT or mark the existing file as being present in a different path.
    I stumbled across the problem in the moment when I first time tried to INSERT a row and got told that
    md5sum gotta be unique.
    Any ideas for design and query? The code example below is incomplete. Especially what I'm looking for is
    how to construct a prepared SQL statement into which I can inject the variable later found (md5sum)
    Whether I should do that by COUNT(*) or a different method?
    Christoph
    Here is my sketchy code (Netbeans project) under construction:
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package testsqlite;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.sql.*;
    import java.util.Iterator;
    import java.util.List;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    * @author chris
    public class Main {
    * @param args the command line arguments
    private static Connection conn;
    private static String sql="INSERT INTO part(name,md5sum) VALUES (?,?)";
    private static PreparedStatement pstmnt,pstmnt_ifexists ;
    private static String sql_ifexists="SELECT COUNT(*) FROM part WHERE md5sum=?"; // ???
    public static void main(String[] args) throws Exception{
    // TODO code application logic here
    System.out.println("Testsuite-Collector\n");
    String path="c:/usr/local/www/data/testsuite/mandanten/chris/probanden";
    File f = new File(path);
    Class.forName ("org.sqlite.JDBC");
    conn =
    DriverManager.getConnection("jdbc:sqlite:c:/users/chris/testsuite/versionen");
    Statement stat = conn.createStatement();
    pstmnt = conn.prepareStatement(sql);
    pstmnt_ifexists = conn.prepareStatement(sql_ifexists);
    // process
    Traverse(f);
    // watch result
    ResultSet rs = stat.executeQuery("select * from part;");
    while (rs.next()) {
    System.out.print("name=" + rs.getString("name") + " ");
    System.out.println("md5sum= " + rs.getString("md5sum"));
    rs.close();
    conn.close();
    private static void Traverse(File f) throws IOException {
    File[] files = f.listFiles();
    for( File file : files) {
    if(file.isDirectory()){
    Traverse(file);
    else {
    try {
    if(file.length() > 0){
    FileInputStream fis = new FileInputStream( file );
    String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex( fis );
    System.out.println(file.length() +" " md5"->"+file.getPath());
    // check whether md5sum is already existing
    pstmnt_ifexists=?????
    pstmnt.setString(1, file.getPath());
    pstmnt.setString(2, md5);
    pstmnt.executeUpdate();
    catch (SQLException e) {
    System.out.println("SQL error:" e.getMessage()"\n");
    }

    And you seriously think that attempting to insert a record and catching the error of it failing is a good design!?!?I certainly do. I agree with Peter here. You can either test for the existence of the record and insert it if absent, or insert the record willy-nilly and catch the exception. The second option is (a) atomic even without transactions and (b) clearly twice as efficient. Same consideration applies to e.g.
    if (!map.containsKey(key))
      map.put(key, value);
    else
      ; // it was already thereas opposed to
    if (!map.put(key, value)
      ; // it was already thereand many other situations of this kind, e.g.
    try
      if (InetAddress.isReachable(ip))
        s = new Socket(ip, port);
      else
        ; // host not up
    catch (ConnectException exc)
      // the host wasn't up during connect
    }as opposed to
    try
      s = new Socket(ip, port);
    catch (ConnectException exc)
      // host not up
    }or
    try
      if (file.exists())
        in = new FileInputStream(file);
      else
        ; // it wasn't there
    catch (IOException exc)
      // it wasn't there, etc ...
    }as opposed to
    try
      in = new FileInputStream(file);
    catch (FileNotFoundException exc)
      // it wasn't there
    }Slight absence of timing window problems in the cases that detect via exceptions, and considerably simpler code. Phobias about how to use exception handling need to be overcome.
    I've also had it seriously argued to me that you shouldn't catch EOFExceptions, merely change the format of your file so you 'know' when one is coming up. Sorry to say that I think this sort of thing is complete rubbish. There is a need for an out of band EOF signal with all the readXXX() methods, and this is it.

  • Oracle + Unix question , Error validation for SQL statements in co process

    Hi,
    If I use co process in a shell script , what is the best way to do the error validation of the execution of any sql statements . I was trying to change the following code to make use of co process concept. When I tried echo $? after the execution of a "wrong statements"
    it is still giving Zero output ( meaning success)
    <<<<<<<<<<<<<<<<<<<<<<<<<<<
    cat ${CFG_DIR}/srs_indx.lst | egrep -v '^#' | egrep -v '^[    ]*$' | while read x
    do
    echo " Processing values :: pre $pre tbl $tbl indx $indx tblspc $tblspc cols $cols param $param" >> ${LOGS_DIR}/srs_indx.log
    sqlplus ${BIZSTG} << EOT >> ${LOGS_DIR}/srs_indx.log
    set verify on timing on term on echo on feedback on serveroutput on
    WHENEVER SQLERROR CONTINUE
    drop index $indx;
    WHENEVER SQLERROR EXIT FAILURE
    alter session set query_rewrite_enabled = true;
    create $pre index $indx on $tbl ($cols)
    tablespace $tblspc
    $param;
    exit
    EOT
    RC=$?
    if ( test $RC -ne 0 )
    then
         ERR_MSG="ERROR in creating index $indx for table $tbl from srs_indx.ksh of $ENVIR : $APP by `whoami`@`hostname` on `date` "
         echo $ERR_MSG >> ${LOGS_DIR}/srs_indx.log
         process_warning ${LOGS_DIR}/srs_indx.log
         exitstat=1
    else
         echo "$indx created at `date`" >> ${LOGS_DIR}/srs_indx.log
    fi
    done
    >>>>>>>>>>>>>>>>>>>>
    Any help will be appreciated .
    with thanks and regards
    Ranjeesh K R

    Hi,
    Thanks for the response, I guess people misunderstood my question .
    My question was about "error handling in case of CO PROCESS". For those who don't know about this, in case CO PROCESS you just need to login once to Oracle. In my above code It is logging in & out for each entry in the list. CO process statements may look Similar to SQL statements in pro*C. In PRO*C we use EXEC, but here print -p statements..
    a sample is given for those who are new to co process.
    sqlplus -s /nolog |& # Open a pipe to SQL*Plus
    print -p -- 'connect user/password@instance'
    print -p -- 'set feed off pause off pages 0 head off veri off line 500'
    print -p -- 'set term off time off'
    print -p -- "set sqlprompt ''"
    print -p -- "select sysdate from dual;"
    read -p SYSDATE
    print -p -- "select user from dual;"
    read -p USER
    print -p -- "select global_name from global_name;"
    read -p GLOBAL_NAME
    print -p -- exit
    echo SYSDATE: $SYSDATE
    echo USER: $USER
    echo GLOBAL_NAME: $GLOBAL_NAME
    But I got stuck during error handling of these SQL statements, especially the $? / $* returns 0 even after an erroneus execution.
    Regards

  • Printing Prepared Statement Query

    Hi all,
    Is it possible to print Prepared Statement query. When i give System.out.println(query);, i get the query with '?' and not with the actual value sent. How can i print the query with the value passed in place of the '?' ?

    Hi all,
    Is it possible to print Prepared Statement
    tatement query. When i give
    System.out.println(query);, i get the query with '?'
    and not with the actual value sent. How can i print
    the query with the value passed in place of the '?' ?The simple answer is that you can't (AFAIK), but some database drivers are able to log the sql statements.
    Kaj

Maybe you are looking for

  • Problem while assigning Servlet to Execute queue

    Hi, We implement a IMS S-CSCF on BEA container 2.2. A call for us may be several times reentrant. Meaning that for one call we have to handle at least three different dialogs but in major use cases, it will be 6 or 7 for our next deployment. We are c

  • XmlDataProvider .... is gone completely in my Xaml file. Why? How many different ways to deal with xml data source through WPF

    I followed a procedure described in a book. 1. insert "Inventory.xml" file to a project "WpfXmlDataBinding" . 2. add the XML data source through the data panel of "blend for 2013", named it "InventoryXmlDataStore" and store it in the current document

  • Change host name on windows 2k3 post successful Essbase 11.1.2.1.0 install

    Hi gurus installed Essbase 11.1.2.1.0 successfully on windows w2k3 ent srever 32 bit can I change the host name to include domain name currently it is xxx.xx.xxx.xxx somehost can it be changed to xxx.xx.xxx.xxx somehost.local.com somehost is hostname

  • Cropping Problem: Image break-up

    Hi So far, I am quite impressed with CS6--the more I use it the better it gets.  However, I am running into an ongoing issue with cropping.  It mainly occurs with stitched panoramas, and happens whether I use RAW, tiffs or jpegs.  Once the image is s

  • Find Profiles without a role

    Good Morning,      I have been working on trying to find a list of all profiles that do not have a role assigned.  I found many tables that hold information of roles to profiles and profiles to authorizations but there does not seem to be a good way