Scope of PreparedStatement

If my logic re-creates the PreparedStatement everytime, do I lose the advantage of the PreparedStatement over the Statement class ? Should I instead try to make the scope of my PreparedStatement reference such that it does not get destroyed? Or is the JDBC driver smart enough to recognize a statement that it has already precompiled, and not recompile it again ?

Speed issues aside, use PreparedStatement whenever you have parameters to the SQL. Don't waste time doing your own date conversions or string ' conversion.
As to speed: depends on the database. E.g. by my measurements, in Oracle a PreparedStatement is never slower than a Statement, and gets a bit faster when re-used (i.e. one use = same speed, many uses = prepared is faster).
How often do you execute your most often executed SQL statement? If statement compilation takes a few microseconds, execution a few milliseconds, and you execute a few times a minute -> who cares. You certainly don't want to keep lots of PS's around; they eat up memory at the server, and the microsecond/millisecond/minute math can't make sense for others than the top few SQL statements at best.
Benchmark your setup: try the program in reply 8 of http://forum.java.sun.com/thread.jsp?thread=504253&forum=48&message=2387589 . Please do tell us what you find out!

Similar Messages

  • How to use "scope " attrubute in useBean tag

    Can anyone please tell me if I can use the same JavaBean Class to hold information form different pages? well, let me explain exactely what I want to do:
    I have a Java bean Class that holds a property 'Name':
    package ContactManager;
    public class Person {
    private String name="%";
    public String getName () {
    return this.name;
    public void setName (String my_name) {
    name = my_name + "%" ;
    I'm using this class to store temporarly the Criteria of search from a JSP/HTML page to send to a database for search and for UPDATE -> this of course is done in different HTML/JSP pages. The problem I have is that the first time I set the properties (when the user make a search) this value remains unchanged [-> the second time when the user asks for update, I try to use the same bean to keep the value => unfortuntly it returns me the old value]
    My question is: is the use of 'scope' attribute of the "jsp:useBean" tag can solve this problem? if yes how to use it? I've tryed to set the scope of the bean to page but that does not help :-(
    Pleaze help, I'm stuck.... Bellow is the 4 JSP pages for:
    - person_search.jsp / person_result.jsp
    - request_modify.jsp/ DoModify.jsp
    1 -person_search.jsp
    <%@ page import="java.sql.*" %>
    <HTML>
    <HEAD><TITLE>Person Search</TITLE></HEAD>
    <BODY><CENTER>
    <form method="POST" action="person_result.jsp">
    Name <input type="text" name="name" size="47"></p>
    <input type="submit" value="Submit" name="B1">
    <input type="reset" value="Reset" name="B2"></p>
    </form></body>
    </html>
    2- person_result.jsp
    <%@ page import="java.sql.*" %>
    <HTML><BODY>
    <jsp:useBean id="theBean" class="ContactManager.Person"/>
    <jsp:setProperty name="theBean" property="*" />
    Name<BR>
    <%
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    System.out.println("JDBC driver loaded");
    catch (ClassNotFoundException e) {
    System.out.println(e.toString());
    %>
    <%
    try {
    Connection con = DriverManager.getConnection("jdbc:odbc:ContactManager");
    Statement s = con.createStatement();
    String sql = "SELECT Client.ClientID, Client.Name FROM Client where Client.Name like " + "'" + theBean.getName() + "'";
    ResultSet rs = s.executeQuery(sql);
    while (rs.next()) {
    String myId = rs.getString(1);
    %>
    <TR>
    <TD><%= myId %></TD>
    <TD><a href="person_detail.jsp?id=<%= myId %>"><%=rs.getString(2)%></a></TD>
    <TD><a href="delete_person.jsp?id=<%= myId %>">Delete</a></TD><BR>
    </TR>
    <%
    rs.close();
    s.close();
    con.close();
    catch (SQLException e) {
    System.out.println(e.toString());
    catch (Exception e) {
    System.out.println(e.toString());
    %>
    </BODY>
    </HTML>
    3- request_modify.jsp
    <%@ page import="java.sql.*" %>
    <html>
    <head><title>AddressBook: Modifying Person <%= request.getParameter ("id") %></title> </head>
    <body bgcolor="#ffffee">
    <%
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    System.out.println("JDBC driver loaded");
    catch (ClassNotFoundException e) {
    System.out.println(e.toString());
    %>
    <%
    int rowsAffected = 0;
    try {
    Connection con = DriverManager.getConnection("jdbc:odbc:ContactManager");
    Statement s = con.createStatement();
    String sql = "SELECT Client.ClientID, Client.Name FROM Client where ClientID ="+ request.getParameter("id");
    ResultSet rs = s.executeQuery(sql);
    if (rs.next()) {
    %>
    Client Name is <input type=text name=name value=<%= rs.getString(2) %>> <br>
    <TD><a href="person_do_modify.jsp?id=<%= rs.getString(1)%>">Confirm Modify</a></TD>
    <%
    rs.close();
    s.close();
    con.close();
    catch (SQLException e) {
    System.out.println(e.toString());
    catch (Exception e) {
    System.out.println(e.toString());
    %>
    </BODY> </HTML>
    4- do_modify.jsp
    <%@ page import="java.sql.*" %>
    <html>
    <head><title>AddressBook: Modifying Address <%= request.getParameter ("id") %></title></head>
    <body bgcolor="#ffffee">
    <jsp:useBean id="theBean" class="ContactManager.Person" scope="page"/>
    <jsp:setProperty name="theBean" property="name"/>
    <%
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    System.out.println("JDBC driver loaded");
    catch (ClassNotFoundException e) {
    System.out.println(e.toString());
    %>
    <%
    int rowsAffected = 0;
    try {
    Connection con = DriverManager.getConnection("jdbc:odbc:ContactManager");
    PreparedStatement preparedStatement = con.prepareStatement ("UPDATE Client SET Name=? WHERE ClientID =?");
    preparedStatement.setString (1, theBean.getName());
    preparedStatement.setString (2, request.getParameter("id"));
    rowsAffected = preparedStatement.executeUpdate ();
    preparedStatement.close ();
    if (rowsAffected == 1) {
    %>
    done
    <%
    else{
    %>
    Not Modified
    <%
    con.close();
    catch (SQLException e) {
    System.out.println(e.toString());
    catch (Exception e) {
    %>
    </BODY></HTML>
    Thank you for the help.
    Sammy

    While a quick search on the <jsp:useBean> tag and the scope attribute will probably yield more information than I can summarize in a few sentences, I'm pretty sure that using the scope="page" attribute on a bean will cause that bean to be instantiated every time the page is loaded. In order for a bean to persist longer than the existance of that page (whether you're loading a new page, or reloading the same one), you'd need to set the scope to session or application (you'd probably want session).

  • Hesitate with Statement and PreparedStatement!!!!!!

    i create a test to make clear the 2 thing's diffrience,
    Test use tomcat4.1.24+mysql,test times more than 15 per test
    situation:
    1:create a Connection to mysql,create a Statement object, use this Statement object to query a sql,use time for 411ms;
    2:create a Connection to mysql,create a PreparedStatement object, use this PreparedStatement object to query a sql with a parameter,use time for 409ms;
    3:create a Connection and a Statement to mysql in the construction method,in the method to query a sql use the current Statement,use time 380 ms;
    4:create a Connection and a PreparedStatement to mysql in the construction method,in the method to query a sql use the current PreparedStatement ,use time 390 ms;
    5:jstl:<sql:setDataSource/>set the scope with the four parameter in (request,page,session,application),use time is all about 411ms;
    so i wanna anybody tell me ,what is the advantage of PreparedStatement.

    A PreparedStatement means you don't have to do anything special if you try to insert a string that contains a quote character. And you don't have to tie your code in knots trying to get your timestamps formatted in just the way your database insists on. The PreparedStatement handles all those issues for you. The Statement doesn't.
    A more realistic benchmark comparison would be:
    1. Create a Connection, create a PreparedStatement, use it as a query 1000 times.
    2. Create a Connection, then 1000 times create a Statement and use it as a query.
    PC&#178;

  • PreparedStatement 와 cursor sharing 파라메터에 관해 질문입니다.

    PreparedStatement 와 cursor sharing 파라메터에 관해 질문입니다.
    cursor_sharing 파라메터를 EXACT 가 아닌 similar, force를 이용하면
    리터럴이나 바인드 변수를 제외한 나머지 문장이 동일하면 같은 문장으로 취급하여
    동일한 실행 계획을 이용한것으로 알고 있습니다.
    그런데 만약 EXACT인경우 는 SQL-PLUS 상에서
    select * from dept where deptno = &dept 이렇게 바인드 변수를 사용해도
    다른 문장으로 처리하더군요.... 그렇다면
    PreparedStatement의 경우는 EXACT일때 어떻게 되는건인가요?
    어떤 jdbc 책도 ps 를 사용하라고 나와있고 오라클 튜닝책에는 cursor_sharing을
    적절하게 사용하라고 되어있습니다.
    두가지에 대해 같이 언급하는것은 없는데....
    EXACT일때도 ps가 가능한것인지 좀 가르쳐 주세요...

    아래는 성능테스트를 한 상황입니다.
    CURSOR_SHARING의 사용
    ===========================================
    Explanation
    1. 용례
    1) initSID.ora에 기술 : CURSOR_SHARING = { FORCE | EXACT }
    2) Scope : Dynamic ( ALTER SESSION, ALTER SYSTEM )
    3) Default Value : EXACT
    2. 설명
    다음과 같은 두 개의 SQL 문장은 sql area의 cursor를 공유하지
    못한다.
    SELECT ename, empno FROM emp where deptno = 10;
    SELECT ename, empno FROM emp where deptno = 20;
    -> 위 sql 문장에서 다른 부분은 모두 동일하나 binding variable을
    사용하지 않고 각각 상수인 10, 20을 사용한다.
    만약 두 가지 sql 문장이 cursor를 공유하도록 하기 위해서는
    sql 문장을 다음과 같이 바꿀 수 있다.
    SELECT ename, empno FROM emp where deptno = :department_no;
    하지만 이와 같이 바꾸는 것이 여의치 않을 경우 init 파라미터 파일이나
    ALTER SYSTEM, ALTER SESSION 등의 명령으로 CURSOR_SHARING 값을
    FORCE로 지정하면 된다.
    3. 고려사항
    CURSOR_SHARING 값을 FORCE로 지정하기 위해서는 다음과 같은 2가지 사항을
    고려하여야만 한다.
    1) SQL area에서 값을 제외한 다른 부분이 모두 동일한 문장이 많이 있는지
    2) library cache miss가 높아 response time이 늦는지
    * DSS 시스템에서는 CURSOR_SHARING 값을 FORCE로 지정할 경우 결과를 예측
    하기 어려우므로 권장하지 않는다. 또한 복잡한 query나 query rewrite,
    stored outline을 사용할 경우에도 CURSOR_SHARING 값을 FORCE로 지정하는
    것을 권장하지 않는다.
    4. 성능 분석
    환경 : Windows NT 4.0 ( Pentium 233MHz 1 CPU, 128M )
    Oracle 8.1.6
    시나리오 : 특정 table에 만 개의 row insert
    1) Binding Variable을 사용하지 않고 CURSOR_SHARING 값이 EXACT인 경우
    -> Total time elapsed : 80,496 msec.
    2) Binding Variable을 사용하지 않고 CURSOR_SHARING 값이 FORCE인 경우
    -> Total time elapsed : 61,699 msec.
    3) Binding Variable을 사용할 경우
    -> Total time elapsed : 21,561 msec.
    위 결과에 따르면 동일한 sql 문장을 반복적으로 처리할 경우 binding
    variable을 사용하는 것이 가장 속도가 빠른 것으로 나타났으며, binding
    variable을 사용하지 않을 경우에도 CURSOR_SHARING 값이 FORCE일 경우
    그렇지 않을 경우 약 23% 정도의 속도 개선 효과가 있음을 알 수 있다.
    글 수정:
    minyh0124

  • PreparedStatement problem

    hi experts,
    i have this simple bean for inserting data into the database...........................
    // EmployeeDataBaseBean.java
    package wh;
    import java.lang.*;
    import java.sql.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class EmployeeDatabaseBean
    String email = "";
    String empname = "";
    String extno = "";
    String cellno = "";
    String remarks = "";
    HttpServletRequest request = null;
    Connection dbConn = null;
    * Set the request object. This is used for getting parameters.
    public void setRequest(HttpServletRequest request)
    this.request = request;
    }//public void setRequest(HttpRequest request)
    * Connect to the database.
    public void connectToDatabase()
    throws Exception
    /* Use JDBC to connect to the SAMPLE database.*/
    Class.forName("COM.ibm.db2.jdbc.app.DB2Driver").newInstance();
    String url = "jdbc:db2:one";
    String dbUser = "";
    String dbPass = "";
    Connection dbConn = DriverManager.getConnection(url);
    /* If the connection fails, throw an Exception.*/
    if(dbConn == null)
    throw new Exception("The database connection failed.");
    System.out.println("called connect inside connnecttodatabase");
    * Run the SELECT statement query to return a single EMPLOYEE record.
    public void runQuery()
    throws Exception
    /* Connect to the database.*/
    connectToDatabase();
    /* Get the EMPNO parameter from the request object.*/
    String empmailParam = request.getParameter("EMAIL");
    /* Build a SQL SELECT statement.*/
    String sql = "SELECT EMAIL, EMP_NAME, EXT_NO, CELL_NO, REMARKS " +
    "FROM CONTACT WHERE EMAIL = ?";
    /* Prepare the SELECT statement.*/
    PreparedStatement statement = dbConn.prepareStatement(sql);
    /* Set the parameter in the SELECT statement and run it.*/
    statement.setObject (1, empmailParam);
    ResultSet result = statement.executeQuery();
    /* Get the result row.*/
    while(result.next())
    email = result.getString("EMAIL");
    empname = result.getString("EMP_NAME");
    extno = result.getString("EXT_NO");
    cellno = result.getString("CELL_NO");
    remarks = result.getString("REMARKS");
    /* Close the connection.*/
    dbConn.close();
    * Insert a record to the database.
    public void insertEmployee()
    throws Exception
    /* Connect to the database.*/
    connectToDatabase();
    System.out.println("connected to db2 through insertemployee");
    /* Get all the parameters from the calling HTML form.*/
    String mailParam = request.getParameter("EMAIL");
    System.out.println("the email is " + request.getParameter("EMAIL"));
    String nameParam = request.getParameter("EMPNAME");
    System.out.println("the name is " + request.getParameter("EMPNAME"));
    int extnoParam = Integer.parseInt(request.getParameter("EXTNO"));
    System.out.println("the extension number is " + request.getParameter("EXTNO"));
    int cellnoParam = Integer.parseInt(request.getParameter("CELLNO"));
    System.out.println("the cellno is " + request.getParameter("CELLNO"));
    String remarksParam = request.getParameter("REMARKS");
    System.out.println("the remark is " + request.getParameter("REMARKS"));
    System.out.println("building sql query");
    /* Build a SQL INSER statement.*/
    String sql = "INSERT INTO CONTACT " + "(EMAIL, EMP_NAME, EXT_NO, CELL_NO, REMARKS) " + " VALUES " + "(?,?,?,?,?)";
    System.out.println("executed sql statement");
    /* Prepare the SELECT statement.*/
    PreparedStatement statement = dbConn.prepareStatement(sql);
    System.out.println("using preparedstatement");
    /* Set the parameters for the INSERT run it.*/
    statement.setString(1, mailParam);
    statement.setString(2, nameParam);
    statement.setInt(3, extnoParam);
    statement.setInt(4, cellnoParam);
    statement.setString(5, remarksParam);
    boolean returnValue = statement.execute();
    /* Close the connection.*/
    dbConn.close();
    System.out.println("query executed");
    }//public void insertEmployee()
    * Return the empNo.
    public String getemail()
    return email;
    * Return the firstNme.
    public String getempname()
    return empname;
    * Return the midInit.
    public String getextno()
    return extno;
    * Return the lastName.
    public String getcellno()
    return cellno;
    * Return the edLevel.
    public String getremarks()
    return remarks;
    //and the html page calling the jsp page which inturn uses the bean.
    //EmployeeInput.html
    <HTML>
    <HEAD>
    <TITLE>
    Employee Input
    </TITLE>
    </HEAD>
    <BODY BGCOLOR="#f0f0ff">
    <H2>Insert An Employee:</H2>
    <BR><FORM NAME="employeeForm" ACTION="EmployeeDisplay.jsp">
    <table border=2>
    <tr>
    <td>EMail:</td>
    <td><INPUT NAME="EMAIL" VALUE="" TYPE="text"></td>
    </tr>
    <tr>
    <td>Employee Name:</td>
    <td><INPUT NAME="EMPNAME" VALUE="" TYPE="text"></td>
    </tr>
    <tr>
    <td>Extension Number:</td>
    <td><INPUT NAME="EXTNO" VALUE="" TYPE="text" LENGTH="6"></td>
    </tr>
    <tr>
    <td>Cell Number:</td>
    <td><INPUT NAME="CELLNO" VALUE="" TYPE="text"></td>
    </tr>
    <tr>
    <td>Remarks:</td>
    <td><INPUT NAME="REMARKS" VALUE="" TYPE="text"></td>
    </tr>
    <tr>
    <td><center><INPUT NAME="submitButton" VALUE="Insert" TYPE="submit"></center></td>
    </tr>
    </FORM>
    </BODY>
    </HTML>
    // the jsp page that uses the bean.
    //EmployeeDisplay.jsp
    <jsp:useBean id="employeeDatabaseBean" class="wh.EmployeeDatabaseBean" scope="request"/>
    <!-- Perform the actions on the bean. -->
    <%
    try
    /* Set the request object.*/
    /* The request object is implicitly available in the JSP page.*/
    employeeDatabaseBean.setRequest(request);
    /* Insert the employee data into the database.*/
    employeeDatabaseBean.insertEmployee();
    /* Run the query to retrieve the employee data from the database.*/
    //employeeDatabaseBean.runQuery();
    catch (Exception e)
    System.out.println(e.getMessage());
    %>
    <HTML>
    <HEAD>
    <TITLE>
    Employee Display
    </TITLE>
    </HEAD>
    <BODY BGCOLOR="#FFFFFF">
    <H2>Employee Record:</H2>
    <BR><FORM NAME="employeeDisplayForm" >
    <BR>Employee No: <INPUT NAME="EMPNO" VALUE="<%= employeeDatabaseBean.getemail() %>" TYPE="text">
    <BR>First Name: <INPUT NAME="FIRSTNME" VALUE="<%= employeeDatabaseBean.getempname() %>" TYPE="text">
    <BR>Mid: <INPUT NAME="MIDINIT" VALUE="<%= employeeDatabaseBean.getextno() %>" TYPE="text" LENGTH="4">
    <BR>Last Name: <INPUT NAME="LASTNAME" VALUE="<%= employeeDatabaseBean.getcellno() %>" TYPE="text">
    <BR>Education Level: <INPUT NAME="EDLEVEL" VALUE="<%= employeeDatabaseBean.getremarks() %>" TYPE="text">
    </FORM>
    </BODY>
    </HTML>
    my problem is that the file runs perfectly on the browser. The issue arises here that the data doesnt gets inserted into the database...................also that the console does not show any error either........what i feel is that the prepared statement isnt functioning properly.......the control doesnt moves beyond the prepared statement
    plz help

    Hello hermione,
    Try to insert a space after end of string in the SQL-statement, just before the qoutes, then it hopefully works, as bellow.
    String sql = "INSERT INTO CONTACT " + "(EMAIL, EMP_NAME, EXT_NO, CELL_NO, REMARKS) " + " VALUES " + "(?,?,?,?,?)";
    //javanalle

  • Using a preparedStatement

    I am passing variables to a preparedStatement (in a class) and want to return a ResultSet with the same preparedStatement. I use the same variables twice in the preparedStatment. Ex.
         getHist.setString(1, fp);
         getHist.setString(2, week_no);
         getHist.setString(3, fp);
         getHist.setString(4, week_no);
    I then want to return the ResultSet back to the same .jsp. I cant seem to get the data back to the page. What am I doing wrong?
    Here is the code for the class:
    package com.flash;
    import java.sql.*;
    import java.util.*;
    public class HistoryInfo{
    String error;
    Connection con;
    public HistoryInfo() {}
    public void connect() throws ClassNotFoundException,
                        SQLException,
                        Exception {
    try {
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
    con = DriverManager.getConnection(
    "jdbc:oracle:thin:@om-ntdb1:1521:flasht", "commgr", "commgr");
    } catch (ClassNotFoundException cnfe) {
    error = "ClassNotFoundException: Could not locate DB driver.";
    throw new ClassNotFoundException(error);
    } catch (SQLException cnfe) {
    error = "SQLException: Could not connect to database.";
    throw new SQLException(error);
    } catch (Exception e) {
    error = "Exception: An unknown error occurred while connecting to database.";
    throw new Exception(error);
    public void disconnect() throws SQLException {
    try {
    if ( con != null ) {
    con.close();
    } catch (SQLException sqle) {
    error = ("SQLException: Unable to close the database connection.");
    throw new SQLException(error);
    public ResultSet getHistory(String fp, String week_no)
                        throws SQLException, Exception {
    ResultSet rs = null;
    if (con != null) {
    try {
         PreparedStatement getHist;
         getHist = con.prepareStatement(
         "SELECT sbu, TO_CHAR(((sum_dollar) + (adj_sum_dollar)),'$999,999,999.99') AS sum_dollar, TO_CHAR(actual_date,'MM/DD/YY') AS actual_date, " +
         "((sum_cases) + (adj_sum_cases)) AS sum_cases, " +
         "((new_order_cases) + (adj_new_order_cases)) AS new_order_cases, " +
         "((total_open_orders) + (adj_total_open_orders)) AS total_open_orders, " +
         "((back_orders) + (adj_back_orders)) AS back_orders, " +
         "TO_CHAR((sum_dollar/sum_cases), '999.99') AS yield " +
         "FROM SUMMARY " +
         "WHERE actual_date BETWEEN (SELECT begin_dt " +
                   "FROM fiscal_calendar " +
                             "WHERE fiscal_period = '?' " +
                             "AND week_number = '?' " +
                             "AND week_number <> '9' " +
                             "AND fiscal_yr = '2003') " +
                        "AND " +
                             "(SELECT end_dt " +
                        "FROM fiscal_calendar " +
                             "WHERE fiscal_period = '?' " +
                             "AND week_number = '?' " +
                             "AND week_number <> '9' " +
                             "AND fiscal_yr = '2003') " +
              "ORDER BY actual_date, sbu ");
         getHist.setString(1, fp);
         getHist.setString(2, week_no);
         getHist.setString(3, fp);
         getHist.setString(4, week_no);
         rs = getHist.executeQuery();
         } catch (SQLException sqle) {
    error = "SQLException: Update failed, possible duplicate entry.";
         throw new SQLException(error);
    } else {
    error = "Exception: Connection to the database was lost.";
         throw new Exception(error);
    return rs;
    Here is the code for the jsp (minus the html):
    <%
    String fp = request.getParameter("fp");
    String week_no = request.getParameter("week_no");
    historyInfo.connect();
    ResultSet rs = historyInfo.getHistory(fp, week_no);
    while (rs.next()) {
    //String sum_dollar = rs.getString("sum_dollar");
    %>
    <%= rs.getString("sum_dollar") %>
    <%
    %>

    From the javadoc for java.sql.ResultSet :
    A ResultSet object is automatically closed when the Statement object that generated
    it is closed, re-executed, or used to retrieve the next result from a sequence of
    multiple results.So your result set is being closed when you return from getHistory() as your Statement will be closed when it goes out of scope, so you can't get any data from it.
    Its better to copy the data into something else and then process that instead.

  • Help.......preparedStatement problem

    hi experts,
    i have this simple bean for inserting data into the database...........................
    // EmployeeDataBaseBean.java
    package wh;
    import java.lang.*;
    import java.sql.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class EmployeeDatabaseBean
    String email = "";
    String empname = "";
    String extno = "";
    String cellno = "";
    String remarks = "";
    HttpServletRequest request = null;
    Connection dbConn = null;
    * Set the request object. This is used for getting parameters.
    public void setRequest(HttpServletRequest request)
         this.request = request;
    }//public void setRequest(HttpRequest request)
    * Connect to the database.
    public void connectToDatabase()
         throws Exception
         /* Use JDBC to connect to the SAMPLE database.*/
         Class.forName("COM.ibm.db2.jdbc.app.DB2Driver").newInstance();
         String url = "jdbc:db2:one";
         String dbUser = "";
         String dbPass = "";
         Connection dbConn = DriverManager.getConnection(url);
         /* If the connection fails, throw an Exception.*/
         if(dbConn == null)
         throw new Exception("The database connection failed.");
         System.out.println("called connect inside connnecttodatabase");
    * Run the SELECT statement query to return a single EMPLOYEE record.
    public void runQuery()
         throws Exception
         /* Connect to the database.*/
         connectToDatabase();
         /* Get the EMPNO parameter from the request object.*/
         String empmailParam = request.getParameter("EMAIL");
         /* Build a SQL SELECT statement.*/
         String sql = "SELECT EMAIL, EMP_NAME, EXT_NO, CELL_NO, REMARKS " +
                                  "FROM CONTACT WHERE EMAIL = ?";
         /* Prepare the SELECT statement.*/
         PreparedStatement statement = dbConn.prepareStatement(sql);
         /* Set the parameter in the SELECT statement and run it.*/
         statement.setObject (1, empmailParam);
         ResultSet result = statement.executeQuery();
         /* Get the result row.*/
         while(result.next())
         email = result.getString("EMAIL");
         empname = result.getString("EMP_NAME");
         extno = result.getString("EXT_NO");
         cellno = result.getString("CELL_NO");
         remarks = result.getString("REMARKS");
         /* Close the connection.*/
         dbConn.close();
    * Insert a record to the database.
    public void insertEmployee()
         throws Exception
         /* Connect to the database.*/
         connectToDatabase();
    System.out.println("connected to db2 through insertemployee");
         /* Get all the parameters from the calling HTML form.*/
         String mailParam = request.getParameter("EMAIL");
         System.out.println("the email is " + request.getParameter("EMAIL"));
         String nameParam = request.getParameter("EMPNAME");
         System.out.println("the name is " + request.getParameter("EMPNAME"));
    int extnoParam = Integer.parseInt(request.getParameter("EXTNO"));
         System.out.println("the extension number is " + request.getParameter("EXTNO"));
         int cellnoParam = Integer.parseInt(request.getParameter("CELLNO"));
         System.out.println("the cellno is " + request.getParameter("CELLNO"));
         String remarksParam = request.getParameter("REMARKS");
    System.out.println("the remark is " + request.getParameter("REMARKS"));
    System.out.println("building sql query");
         /* Build a SQL INSER statement.*/
         String sql = "INSERT INTO CONTACT " + "(EMAIL, EMP_NAME, EXT_NO, CELL_NO, REMARKS) " + " VALUES " +     "(?,?,?,?,?)";
         System.out.println("executed sql statement");
         /* Prepare the SELECT statement.*/
         PreparedStatement statement = dbConn.prepareStatement(sql);     
    System.out.println("using preparedstatement");
         /* Set the parameters for the INSERT run it.*/
         statement.setString(1, mailParam);
         statement.setString(2, nameParam);
         statement.setInt(3, extnoParam);
         statement.setInt(4, cellnoParam);
         statement.setString(5, remarksParam);
         boolean returnValue = statement.execute();
         /* Close the connection.*/
         dbConn.close();
         System.out.println("query executed");
    }//public void insertEmployee()
    * Return the empNo.
    public String getemail()
         return email;
    * Return the firstNme.
    public String getempname()
         return empname;
    * Return the midInit.
    public String getextno()
         return extno;
    * Return the lastName.
    public String getcellno()
         return cellno;
    * Return the edLevel.
    public String getremarks()
         return remarks;
    //and the html page calling the jsp page which inturn uses the bean.
    //EmployeeInput.html
    <HTML>
    <HEAD>
    <TITLE>
    Employee Input
    </TITLE>
    </HEAD>
    <BODY BGCOLOR="#f0f0ff">
    <H2>Insert An Employee:</H2>
    <BR><FORM NAME="employeeForm" ACTION="EmployeeDisplay.jsp">
    <table border=2>
    <tr>
    <td>EMail:</td>
    <td><INPUT NAME="EMAIL" VALUE="" TYPE="text"></td>
    </tr>
    <tr>
    <td>Employee Name:</td>
    <td><INPUT NAME="EMPNAME" VALUE="" TYPE="text"></td>
    </tr>
    <tr>
    <td>Extension Number:</td>
    <td><INPUT NAME="EXTNO" VALUE="" TYPE="text" LENGTH="6"></td>
    </tr>
    <tr>
    <td>Cell Number:</td>
    <td><INPUT NAME="CELLNO" VALUE="" TYPE="text"></td>
    </tr>
    <tr>
    <td>Remarks:</td>
    <td><INPUT NAME="REMARKS" VALUE="" TYPE="text"></td>
    </tr>
    <tr>
    <td><center><INPUT NAME="submitButton" VALUE="Insert" TYPE="submit"></center></td>
    </tr>
    </FORM>
    </BODY>
    </HTML>
    // the jsp page that uses the bean.
    //EmployeeDisplay.jsp
    <jsp:useBean id="employeeDatabaseBean" class="wh.EmployeeDatabaseBean" scope="request"/>
    <!-- Perform the actions on the bean. -->
    <%
    try
    /* Set the request object.*/
    /* The request object is implicitly available in the JSP page.*/
    employeeDatabaseBean.setRequest(request);
    /* Insert the employee data into the database.*/
    employeeDatabaseBean.insertEmployee();
    /* Run the query to retrieve the employee data from the database.*/
    //employeeDatabaseBean.runQuery();
    catch (Exception e)
    System.out.println(e.getMessage());
    %>
    <HTML>
    <HEAD>
    <TITLE>
    Employee Display
    </TITLE>
    </HEAD>
    <BODY BGCOLOR="#FFFFFF">
    <H2>Employee Record:</H2>
    <BR><FORM NAME="employeeDisplayForm" >
    <BR>Employee No: <INPUT NAME="EMPNO" VALUE="<%= employeeDatabaseBean.getemail() %>" TYPE="text">
    <BR>First Name: <INPUT NAME="FIRSTNME" VALUE="<%= employeeDatabaseBean.getempname() %>" TYPE="text">
    <BR>Mid: <INPUT NAME="MIDINIT" VALUE="<%= employeeDatabaseBean.getextno() %>" TYPE="text" LENGTH="4">
    <BR>Last Name: <INPUT NAME="LASTNAME" VALUE="<%= employeeDatabaseBean.getcellno() %>" TYPE="text">
    <BR>Education Level: <INPUT NAME="EDLEVEL" VALUE="<%= employeeDatabaseBean.getremarks() %>" TYPE="text">
    </FORM>
    </BODY>
    </HTML>
    my problem is that the file runs perfectly on the browser. The issue arises here that the data doesnt gets inserted into the database...................also that the console does not show any error either........what i feel is that the prepared statement isnt functioning properly.......the control doesnt moves beyond the prepared statement
    plz help

    You have defined a Connection object in the beginning of the class. And then you wrote the following connection in a function:
    /* Use JDBC to connect to the SAMPLE database.*/
    Class.forName("COM.ibm.db2.jdbc.app.DB2Driver").newInstance();
    String url = "jdbc:db2:one";
    String dbUser = "";
    String dbPass = "";
    /**************************************//Problem is here */
    Connection dbConn = DriverManager.getConnection(url);
    /* If the connection fails, throw an Exception.*/
    if(dbConn == null)
    throw new Exception("The database connection failed.");
    System.out.println("called connect inside connnecttodatabase");
    Since you are trying the create the object inside the function. Here you said:
    Connection dbConn = DriverManager.getConnection(url);
    In this code dbCon cannot to point to your class level ( which you have defined in the declaration section) dbConn object. Hence this dbConn treated as local memeber to this function. That's it.
    Regards,
    Sudheer Varma Dandu

  • PreparedStatements very slow

    Here's the code:
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection con = DriverManager.getConnection("jdbc:oracle:thin:@remote.oracle.com:1521:TEST", "user", "pwd");
    long $$ts = new java.util.Date().getTime();
    long $$ts2;
    for(int i=0; i<3; i++) {
         PreparedStatement stmt = con.prepareStatement("SELECT * from FB_VALID_VALUES_VIEW WHERE ques_idseq=?");
         stmt.setString(1, "AAA");
         $$ts = new java.util.Date().getTime();
         ResultSet res = stmt.executeQuery();
         $$ts2 = new java.util.Date().getTime() - $$ts;
         $$ts = new java.util.Date().getTime();
         System.out.println("TIMESTAMP: " + $$ts2);
         res.close();
         stmt.close();
    The result of the execution is consistently over 2 seconds.
    Note how I'm only measuring this line:
    ResultSet res = stmt.executeQuery();
    Also note, this is going against a view, and returns 0 results.
    The same program using a Statement instead returns in dozens of millisecond. So, in this particular case, using a preparedStatement is about 250 times slower.
    This is a huge problem, but replacing all PreparedStatements by Statements would also be problematic, for obvious reasons.
    Can someone explain this behavior?
    Thanks,
    Christophe.

    For the very code below, Prepared Statement would not make sense. Heres why:
    We need to understand how a prepared statement works.
    When a database receives a statement, the database engine first parses the statement and looks for syntax errors. Once the statement is parsed, the database needs to figure out the most efficient way to execute the statement. This can be computationally quite expensive. The database checks what indexes, if any, can help, or whether it should do a full read of all rows in a table. Databases use statistics on the data to figure out what is the best way. Once the query plan is created then it can be executed by the database engine.
    It takes CPU power to do the access plan generation. Ideally, if we send the same statement to the database twice, then we'd like the database to reuse the access plan for the first statement. This uses less CPU than if it regenerated the plan a second time.
    Databases are tuned to do statement caches. They usually include some kind of statement cache. This cache uses the statement itself as a key and the access plan is stored in the cache with the corresponding statement. This allows the database engine to reuse the plans for statements that have been executed previously. For example, if we sent the database a statement such as "select a,b from t where c = 2", then the computed access plan is cached. If we send the same statement later, the database can reuse the previous access plan, thus saving us CPU power.
    Note however that the access plan is cached per physical connection. In the code sample given by you, there is one physical connection for which the statement is prepared once giving it no scope for reuse.
    To make sense out of the sample code you have provided,
    PreparedStatement stmt = con.prepareStatement("SELECT * from FB_VALID_VALUES_VIEW WHERE ques_idseq=?");
    for(int i=0; i<3; i++) {
    stmt.setString(1, "AAA");
    Cheers,
    Sunil

  • How to print Integrity sql in the preparedstatement?

    How to print Integrity sql in the preparedstatement?
    Connection conn = null;
    String sql = "select * from person where name=?";
    PreparedStatement ps = conn.prepareStatement(sql);
    ps.setObject(1, "robin");
    ps.executeQuery();
    i'm wants print Integrity sql.
    For example:select * from person where name='robin'
    How should I do?
    thanks a lot!

    PreparedStatement doesn't offer methods for that. You can write your own implementation of PreparedStatement which wraps the originating PreparedStatement and saves the set* values and writes it to the toString().
    If needed, myself I just print the sql as well as the values-being-set to the debug statement.Logger.debug(query + " " + values);

  • PreparedStatement not working

    Hi,
    I am having some problem using PreparedStatement.executeUpdate() . I want to be able to prepare several queries before commiting and I wrote this just to test it
    PreparedStatement stmt= aConnection.prepareStatement("update trans_test1 set field1='a text field' where field1='other text'");
              stmt.executeUpdate();
              aConnection.commit();
              stmt.close();
              aConnection.close();
    when it hits this line "stmt.executeUpdate();" the program just stops running and after a while throws this error.
    java.sql.SQLException: Lock wait timeout exceeded; try restarting transaction
    I set the auto commit to false but I still can't get it working and do not understand the problem. Any one can help?
    Thanks so much
    Alejo

    Hi,
    I am having some problem using
    PreparedStatement.executeUpdate() . I want to be able
    to prepare several queries before commiting and I
    wrote this just to test it
    PreparedStatement stmt=
    aConnection.prepareStatement("update trans_test1 set
    field1='a text field' where field1='other text'");
              stmt.executeUpdate();This is wrong in so many ways:
    (1) Use the bind variables.
    (2) Close resources properly in a finally block.
    (3) You don't show where you set auto commit to false
    (4) You don't show where you rollback in the event of a failure.
    >
    I set the auto commit to false but I still can't get
    it working and do not understand the problem. Any one
    can help?A snippet like this isn't enough. Post all the code.
    Which database are you using, and which driver?
    %

  • Oracle, SELECT IN and PreparedStatement.setArray

    I want to execute the following query: SELECT * FROM SOMETABLE WHERE IDFIELD IN (?)
    The number of values in the IN list is variable. How can I do this with a prepared statement?
    I am aware of the different alternatives:
    1) Keep a cache of prepared statement for each sized list seen so far.
    2) Keep a cache of prepared statements for different sizes (1, 5, 10, 20) and fill in the left over parameter positions with the copies first value.
    They both have the disadvantage that there could be many prepared statements for each query that get used once, and never used again.
    I have tried this:
    stmt.execute ("CREATE OR REPLACE TYPE LONGINTLIST AS TABLE OF NUMBER(15)");
    ArrayDescriptor desc = ArrayDescriptor.createDescriptor ("LONGINTLIST", conn);
    long idValues [] = {2, 3, 4};
    oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY (desc, conn, idValues);
    PreparedStatement query = conn.prepareStatement ("SELECT * FROM MYTABLE WHERE ID_FIELD IN (?)");
    query.setArray (1, paramArray);
    But Oracle gives a data conversion error.
    I then tried this:
    PreparedStatement query = conn.prepareStatement ("SELECT * FROM MYTABLE WHERE ID_FIELD IN (SELECT * FROM TABLE (?))");
    This works and the rows are returned, but the Oracle optimizer does not like it very much, since it always does a full table scan even though there is a primary key index on ID_FIELD.
    Any ideas?
    I also tried this:
    OraclePreparedStatement oraQuery = (OraclePreparedStatement) query;
    oraQuery.setARRAY (1, paramArray);
    But same behavior.
    Roger Hernandez

    Please re-read the original message. As I mentioned,
    I am aware of the two commonly used alternatives.No actually the most used alternative is to build the SQL dynamically each time.
    I know how to get both of them to work, and have used
    both alternatives in the past. The downside to both
    these approaches is that you need to save multiple
    prepared statements for each query. What I am trying
    to find is a way of having only one saved prepared
    statement for a query having a variable number of IN
    clause parameters.You could probably use a stored procedure that takes an 'array' and then do the processing in the stored proc to handle each array element.
    However, your database might not support that stored procs or arrays. Or it might not cache it with arrays. And the overhead of creating the array structure or processing it in the proc might eat any savings that you might gain (even presuming there is any savings) by using a prepared statement in the first place. Of course given that you must be using an automated profiling tool and have a loaded test environment you should be able to easily determine if this method saves time or not.
    Other than that there are no other solutions.

  • What deterimes the amount of data in a waveform from a TDS 1012 scope

    Hello,
       What determines the amount of data that is in a waveform that comes out of a TDS 1012 scope? I am assuming that I will have to look at the driver vi to determine the commands sent to the scope to figure it out. I am in a situation that I need to have the y axis to have a high resolution, that results in very little data being collected from the scope.
    Regards,
    Kaspar
    Regards,
    Kaspar

    Hello,
        The amount of data that comes out of the TDS 1012 scope is determined by the data start (DATaTARt)  and data stop (DATaTOP)  commands that are defined on page 58 (2-38) in the  346 page programming manual for the scope. I found of that the data start was not set to 1, which is the beginning of the data.
        I also had a very low level signal on channel that was all most unreadable by the scope that caused me to think that I was not getting all of the data.
    Regards,
    Kaspar
    Regards,
    Kaspar

  • Accessing message out of scope

    Hi all,
    I have a message "Message_A" constructed inside the scope shape and being sent to the send port. Now when any exception occurs i need to log the details to the database. I have an exception handler with the expression in the construct message as
    below
    Excep_message(FILE.ReceivedFileName)=Message_A(FILE.ReceivedFileName);
    I received the error "use of unconstructed message 'Message_A'" when compiling the project. For this error i constructed the message "Message_A" before the scope shape as below.
    Message_A=null;
    Message_A(BTS.Operation)="Operation";
    Then i was able to compile the project without any error. When i deployed and the application exectued i got the below error.
    xlang/s engine event log entry: Uncaught exception (see the 'inner exception' below) has suspended an instance of service 'Ibox.UNEDIFACT.COPARN.Orchestration.CoparnOrchestration_AEJEA(3f2f8342-08cd-6b69-c647-d13dc48b24ad)'.
    The service instance will remain suspended until administratively resumed or terminated.
    If resumed the instance will continue from its last persisted state and may re-throw the same unexpected exception.
    InstanceId: 5bbb4a82-19ae-48bc-8bc0-b8c992088c68
    Shape name: ConstructMessage_1
    ShapeId: a849f763-3f7f-4bc3-bea2-9887fc3c7415
    Exception thrown from: segment 1, progress 10
    Inner exception: The part 'part' of message 'Message_A' contained a null value at the end of the construct block.
    Exception type: NullPartException
    Source: Microsoft.XLANGs.Engine
    Target Site: Void ConstructionCompleteEvent(Boolean)
    The following is a stack trace that identifies the location where the exception occured
       at Microsoft.XLANGs.Core.Part.ConstructionCompleteEvent(Boolean fKillUnderlyingPart)
       at Microsoft.XLANGs.Core.XMessage.ConstructionCompleteEvent(Boolean killUnderlyingPartWhenDirty)
       at Ibox.UNEDIFACT.COPARN.Orchestration.CoparnOrchestration_AEJEA.segment1(StopConditions stopOn)
       at Microsoft.XLANGs.Core.SegmentScheduler.RunASegment(Segment s, StopConditions stopCond, Exception& exp)
    Kindly assist why the null error is being raised even when i have assigned the Message_A with a value.
    Regards, Vivin.

    You assigned Message_A with a null value, that's where the null error is raised! 
    To assign Message_A with a value you will need to execute a mapping or assign it with a variable that contains a xmlDocument if your Message_A is a generic message.
    Another question: why do you want a null Message_A on your messagebox? Is that the required behavior?
    Be sure to also check following blog by Paole, it contains everything you need to know about processing and creating xlangmessages:
    http://blogs.msdn.com/b/appfabriccat/archive/2010/06/23/4-different-ways-to-process-an-xlangmessage-within-an-helper-component-invoked-by-an-orchestration.aspx
    Glenn Colpaert - Microsoft Integration MVP - Blog : http://blog.codit.eu

  • What is the scope of implicit loop variables?

    Hi,
    I'm facing some strange error from the ABSL editor (syntax checker).
    In ABSL the loop variables are implicit and don't have to be declared in the head section of the script.
    My question now is simple: How is the scope/visibility of such loop variables specified ?
    There's a complete code snippet below.
    In line no.9, there's the first time use of implicit loop variable 'task_inst'.
    Because of type inference, it will be typed as MasterDataWanneBe/Tasks (which is my own BO type).
    In line no.20, I want to use the same variable name in a different loop, outside the parenthesis/scope of the first first use.
    Now the ABSL syntax checker complains about incompatible types (see code snippet)
    Thus the type inference should result in the, (lets say 'local') type Project/Task, which is the one I was querying for.
    To me it looks like, that loop variables implicitly get a global scope (hopefully bound to this ABSL file only).
    I would like to see the scope/visibility of loop variables restricted to the parenthesis.
    In other words only inside the loop.
    Hint
    I heard (from little sparrows), that local variable scoping is not possible because of underlying
    generated ABAP code. If so, than it would be helpful to print warnings, in case of types are compatible
    but used in different scopes. Think about the unintended side effects.
    import ABSL;
    import AP.ProjectManagement.Global;
    var query_tasks;
    var query_tasks_param;
    var query_tasks_result;
    foreach (empl_inst in this.Employees) {
         foreach (task_inst in empl_inst.Tasks) {
             //   ^^^^^^^^^  first time use
              task_inst.Delete();
    // ===========================================================================
    query_tasks = Project.Task.QueryByResponsibleEmployee;
    query_tasks_param = query_tasks.CreateSelectionParams();
    query_tasks_result = query_tasks.Execute(query_tasks_param);
    foreach (task_inst in query_tasks_result) {
          // ^^^^^^^^^ Error: 4
          // The foreach loop variable is already inferred to an incompatible type:
          // Node(MasterDataWanneBe/Tasks). Expected Node(Project/Task)

    Yes, variable declarations in ByD Scripting Language indeed have (snippet) global visibility. In the FP 3.0 release the variables can be declared anywhere in the snippet (not only in the beginning, as with FP 2.6), however still not within code blocks, i.e. within curly braces ({}). Therefore variable name shadowing is still not supported and because of the global visibility of variables they cannot be reused for a different type, later in the same snippet. This is because of the statically typed nature of ByD Script, despite the type inference convenience.
    Kind regards,
    Andreas Mueller

  • Problem with PreparedStatement

    I'm using a statement which needs to determine if the value is in a group.
    The statement will be
    "select name,age,occupation from personnel where age in ?"
    ps.setString(1, "(20,21,22)");
    I've also tried
    ps.setString(1, "('20','21','22')");
    Neither brings back any values in the result set.
    I can't figure out how to print what the preparedstatement looks like after setting the value.
    I look in the table and there are records with age 20, 21, 22.. and age is set as a string.

    Try this:
        query_B = "select tablename.blah_blah_blah"
                + "  from tablename"
                + " where tablename.etc is null"
                + "   and table.blah_term_code       in (?, ?)"
                + " order by 1, 2, 4, 7";
          String[] in_sem_dt = { "200307", "200308" };
          pstmt_B = con.prepareStatement( query_B );
          pstmt_B.setString( 1, in_sem_dt[0] );
          pstmt_B.setString( 2, in_sem_dt[1] );
          rs_B = pstmt_B.executeQuery();~Bill

Maybe you are looking for