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

Similar Messages

  • PreparedStatement problem in Oracle OTD(JCAPS 5.1.3)

    Hi,
    I encountered a problem with Oracle-eway-generated PreparedStatements when trying to build a project in enterprise designer . I know that without using any prepraredstatement, my project builds fine. Below is the text on the error pop-up window:
    java.lang.NullPointerException
    at com.stc.codegen.OTDImpl.model.OTDCodeletFactory$ArtifactKey.hashCode(OTDCodeletFactory.java:136)
    at java.util.HashMap.hash(HashMap.java:261)
    at java.util.HashMap.containsKey(HashMap.java:339)
    at com.stc.codegen.OTDImpl.model.OTDCodeletFactory.getOtdFromBuisnessProcess(OTDCodeletFactory.java:207)
    at com.stc.codegen.OTDImpl.model.OTDCodeletFactory.createCodelets(OTDCodeletFactory.java:285)
    at com.stc.codegen.frameworkImpl.model.DeploymentVisitorImpl.process(DeploymentVisitorImpl.java:382)
    at com.stc.codegen.frameworkImpl.model.DeploymentVisitorImpl.process(DeploymentVisitorImpl.java:308)
    at com.stc.codegen.frameworkImpl.model.DeploymentVisitorImpl.traverseDeployment(DeploymentVisitorImpl.java:268)
    at com.stc.codegen.driver.module.DeploymentBuildAction.loadCodeGen(DeploymentBuildAction.java:923)
    at com.stc.codegen.driver.module.DeploymentBuildAction.access$1000(DeploymentBuildAction.java:174)
    at com.stc.codegen.driver.module.DeploymentBuildAction$1.run(DeploymentBuildAction.java:599)
    at org.openide.util.Task.run(Task.java:136)
    [catch] at org.openide.util.RequestProcessor$Processor.run(RequestProcessor.java:599)In order to isolate the problem, I have created a simplified project which just reads a text message and writes the message into the Oracle database with the help of a PreparedStatement. I had an error as well;
    "Oracle eway code generation error(ERROR_CODEGEN_BPEL_CODELET_GENERAL)"
    Caused by: com.stc.codegen.framwork.model.CodeGenException: Error when generating OTD code ...Exception: Invalid parameter type: Class: [TEST] Object: [Param1] Param Type: [VARCHAR].(ERROR_CODEGEN_DB)(ERROR_CREATE_OTD)I think that there is a conflict between the parameters in Oracle and the parameters in the code. Somehow, Oracle eway cannot get the parameter type from database correctly.
    Is there a solution for this? I couldn't find any patches/updates for Enterprise designer or eway. Can you point me to right direction if there is any.
    Thanks in advance,
    Mete

    Hi there,
    (I think) I have found the solution. When designing OTD, I have mapped VARCHAR2 column as CHAR. Somehow, JCAPS throws a code generation exception if the field is not mapped as a CHAR for a VARCHAR2 database column.

  • JDBC Batch Updates & PreparedStatement problems (Oracle 8i)

    Hi,
    we're running into problems when trying to use JDBC Batch Updates with PreparedStatement in Oracle8i.
    First of all, Oracle throws a SQLException if one of the statements in the batch fails (e.g. because of a unique constraint violation). As far as I understand, a BatchUpdateException should be thrown?
    The next problem is much worse:
    Consider this table:
    SQL> desc oktest
    ID NOT NULL NUMBER(10)
    VALUE NOT NULL VARCHAR2(20)
    primary key is ID
    When inserting in through batch updates with a PreparedStatement, I can pass 'blah' as a value for ID without getting an exception (Oracle silently converts 'blah' to zero). Only when the offending statement is the last statement in the batch, Oracle throws an exception (again, SQLException instead of BatchUpdateException).
    Any comments/suggestions are appreciated.
    E-mail me if you want to see the code...
    Thanks,
    Oliver
    Oracle version info:
    (Enterprise Edition Release 8.1.6.0.0, JServer Release 8.1.6.0.0, Oracle JDBC driver 8.1.6.0.0 and 8.1.7.0.0 (we're using the 'thin' driver)
    CLASSPATH=/opt/oracle/product/8.1.7/jdbc/lib/classes12.zip:...
    null

    Please refer
    http://www.oracle.com/technology/products/oracle9i/daily/jun07.html

  • 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

  • PreparedStatement problems

    I've been working on converting a number of my statements to PreparedStatements for the past couple of days on the advice of several posters concerning security issues. I'm having a couple of problems, however, and I hope somebody can help me out.
    First problem: Can't see the finished SQL. Is there a simple method for retrieving the code a PreparedStatement is actually passing to the DB?
    Second problem (the one I'm trying to debug for): I have a few queries that I know retrieve results when I do them manually using the parameters I think I'm passing, but the resultset from the PS is empty. One theory I have is maybe I'm being too sloppy, using the same PreparedStatement object for multiple queries with varying parameter counts without doing any manual cleanup in between. For example, I have a query that follows a call with no parameters that comes back empty, though it has results when I try it on the DB. I could do the no param call without a PS object, but I'm not sure if that's the problem. Here's the code:
    sql = "SELECT sequence.Currval seq FROM Dual";
    ps = connection.prepareStatement(sql);
    rs = ps.executeQuery();
    rs.next();
    seq = rs.getString("seq");
    sql = "SELECT x FROM xtable WHERE y = ?";
    ps = connection.prepareStatement(sql);
    ps.setString(1, ystring);
    rs = ps.executeQuery();
    rs.next();
    ...at which point I get the "exhausted resultset" message. I've printlned sql and ystring so I don't think there's anything wrong with the statement as written, but due to my first problem above, I can't be sure.
    Thanks in advance!

    PreparedStatements work perfectly well, so you
    must be doing something wrong. My guess is
    maybe your ystring variable is not what you thinkit
    is. Show an example ystring value which returns an
    empty resultset, and what you pass to the database
    when you do the manual query with the allegedlysame
    value which gives you a nonempty resultset.
    And by the way, yes you are being too sloppy. You
    need to close those statements and resultsets.
    ps = connection.prepareStatement(sql);
    rs = ps.executeQuery();
    rs.close();
    ps.close();
    ps = connection.prepareStatement(otherSQL);
    rs = ps.executeQuery();
    ...Well, no need to get snippy, but you're right.You've not been around here much, eh?
    Somebody here pointed out that the sql statement
    t with which PreparedStatement is initialized cannot
    be swapped in as I had been doing. eh? You are doing this:sql = "SELECT sequence.Currval seq FROM Dual";
    ps = connection.prepareStatement(sql); // ps is a reference to a new PreparedStatement
                         // returned by the connection
    rs = ps.executeQuery();
    rs.next();
    seq = rs.getString("seq");
    sql = "SELECT x FROM xtable WHERE y = ?";
    ps = connection.prepareStatement(sql);// ps is a brand new reference to a new PreparedStatement
                         // returned by the connection

  • Preparedstatement problem in oracle jdbc 10.1.0, 10.2.0

    Hello,
    Im using oracle jdbc to connect oracle9.0.1.0.1
    i have a table like
    id-NUMBER
    RESULT-VARCHAR2(100)
    E_DATE-DATE
    STATE-VARCHAR2(1)
    when i write the code like
    "update TBMIS_AUDIT_ISSUE_PROJECT set RESULT=? , E_DATE=?      where PROJ_ID=? and ISSUE_NO=?"
    pstmt.setstring(1, "Test");using preparedstatement, the result column will not be updated correct(ex:%|st).
    but if i change the order of columns like:
    "update TBMIS_AUDIT_ISSUE_PROJECT set E_DATE=?  RESULT=?   where PROJ_ID=? and ISSUE_NO=?"
    pstmt.setstring(2, "Test");it will be correct.
    when i put the column which type is VARCHAR2 in the first place like:
    "update TBMIS_AUDIT_ISSUE_PROJECT set STATE=?, E_DATE=?  RESULT=?   where PROJ_ID=? and ISSUE_NO=?"
    pstmt.setstring(1, "1");the same, the state column will not be updated correct(ex:%)
    but result column will be correct
    looks something wrong in preparedstatement at jdbc 10.1.0 or 10.2.0
    it works well when the driver is jdbc 8.1.7(classes12.zip)
    or working without preparedstatement
    so. is it the bug? or something i missed
    thanks

    and..
    it happened when
    VARCHAR2( size ) less then 1829
    when varchar2 ( size > 1829)
    it doen not happend..
    my table scheme like this
    create table TBMIS_AUDIT  (
       ID                   NUMBER(10)                     not null,
       S_DATE               DATE,
       E_DATE               DATE,
       NOTE                 VARCHAR2(200),
       STATUS             VARCHAR2(1)
    );my code is
    String sql = "update TBMIS_AUDIT set  NOTE=? , S_DATE=?"
                    + ",  STATUS=? where ISSUE_NO=?";
    PreparedStatement pstmt = con.prepareStatement(sql);
    pstmt.setString(1, "ok!!");
    pstmt.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
    pstmt.setString(3, "1");
    pstmt.setString(4, "1");the note column will be filled with some wrong character
    if NOTE is VARCHAR2(2000), it works well again..
    or changing E_DATE to Timestamp in oracle

  • urgent database PreparedStatement problem

    i have tried the following codes for many many times but it still cant work does anyone know why? please help, thank you.
    codes segment:
    PreparedStatement update = connection.prepareStatement(
    "UPDATE OutgoingQueue SET statusEmulator = ? and dateOut = ? WHERE receiverContact = ? and receiverLocation='?' and dateProcessed= ?");
    update.setBoolean(1,msg.getStatus());
    update.setTimestamp(2,dateSent);
    update.setInt(3,contact);
    update.setString(4,location);
    update.setTimestamp(5,dateProcessed);
    update.executeUpdate();
    stacktrace:
    java.lang.ArrayIndexOutOfBoundsException
         at sun.jdbc.odbc.JdbcOdbcPreparedStatement.clearParameter(JdbcOdbcPreparedStatement.java:1026)
         at sun.jdbc.odbc.JdbcOdbcPreparedStatement.setTimestamp(JdbcOdbcPreparedStatement.java:908)
         at DBOutgoingQueue.updateStatus(DBOutgoingQueue.java:124)
         at DBOutgoingQueue.main(DBOutgoingQueue.java:191)

    Hi,
    First of all the SQL query it self is wrong.
    You have given
    "UPDATE OutgoingQueue SET statusEmulator = ? and dateOut = ? WHERE receiverContact = ? and receiverLocation='?' and dateProcessed= ?");
    For Update query you need to give the values camma seperated and not to use "and".
    "UPDATE OutgoingQueue SET statusEmulator = ?,dateOut = ? WHERE receiverContact = ? and receiverLocation='?' and dateProcessed= ?"
    Simillarly before executing the query from java try to executed the same query with values from Oracle.
    Regards,
    DARMA

  • Mysql PreparedStatement problem

    Hi
    I am having trouble updating a database with PreparedStatement. I am using two place holders one of theme which is a String (descr) fails to update.
    I am using
    Connector/J 3.1.13 with mysql 1.4
    here is my code
                        PreparedStatement pstmt = PrimaryConWrapper.getConnection().prepareStatement("INSERT INTO INVOICE_ENTRYES(i_id,descr,value,ts) VALUES("+id+",?,?,0)");
                        for(String eDescr:inve.keySet()){
                            pstmt.clearParameters();
                            int val = inve.get(eDescr);
                            pstmt.setString(1,eDescr);
                            pstmt.setInt(2,val);
                            int rts = pstmt.executeUpdate();
                            assert (rts==2):"In valid number of records updated "+rts;
                        }and I am getting an AssertionError
    Exception in thread "main" java.lang.AssertionError: In valid number of records updated 1
    and my daya base looks like this
    mysql> SELECT * FROM INVOICE_ENTRYES;
    +----+------+-------+------------+---------------------+
    | id | i_id | descr | value      | ts                  |
    +----+------+-------+------------+---------------------+
    | 33 |   13 |       |   50396417 | 0000-00-00 00:00:00 |
    | 34 |   13 |       | 1969358848 | 0000-00-00 00:00:00 |
    | 35 |   13 |       | 1750080256 | 0000-00-00 00:00:00 |
    | 36 |   13 |       | 1868762368 | 0000-00-00 00:00:00 |
    +----+------+-------+------------+---------------------+

    I cannot close the connection in my code because the connection is universal per login. How ever I tried you solution and I get this exception. I am not sure why this is but it could be because of the timestamp value.
                private int add(Invoice in)throws UnknownTypeException,DataSourceException,TypeMismatchException{
                    Connection con = null;
                    try{
                    if(checkName(in))throw new TypeMismatchException("Invoice "+in.getName()+" already exists");
                        String name = in.getName();
                        String descr = in.getDescr();
                        Date date = in.getDate();
                        //invlice entry map
                        Map<String,Integer> inve = in.getEntries();
                        int spId = in.getParent().getId();
                        int jobId = in.getJobMeta().getId();
                        Statement stmt = PrimaryConWrapper.getConnection().createStatement(
                                ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE);
                        stmt.executeUpdate("INSERT INTO INVOICES(dt,name,descr,sp_id,j_id,ts) VALUES('"+date+"','"+name+"','"+descr+"',"+spId+
                                ","+jobId+",0)",Statement.RETURN_GENERATED_KEYS);
                        ResultSet rs = stmt.getGeneratedKeys();
                        boolean chk = rs.next();
                        assert chk :"no keys returned";
                        int id = rs.getInt(1);
                        assert !rs.next():"morethan one key returned";
                        rs.close();
                        stmt.close();
                        con = PrimaryConWrapper.getConnection();
                        con.setAutoCommit(false);
                        PreparedStatement pstmt = PrimaryConWrapper.getConnection().prepareStatement("INSERT INTO INVOICE_ENTRYES(i_id,descr,value,ts) VALUES(?,?,?,?)");
                        for(String eDescr:inve.keySet()){
                            pstmt.clearParameters();
                            int val = inve.get(eDescr);
                            pstmt.setInt(1,id);
                            pstmt.setString(2,eDescr);
                            pstmt.setInt(3,val);
                            pstmt.setInt(4,0);
                            System.out.println(eDescr+","+val);
                            int rts = pstmt.executeUpdate();
                            assert (rts==1):"In valid number of records updated "+rts;
                        con.commit();
                        pstmt.close();
                        return id;
                    catch(SQLException sqle){
                        try{if(con!=null)con.rollback();}catch(Exception e){}
                        throw new DataSourceException("could not add Invoice",sqle);
                    finally{
                        try{if(con!=null)con.setAutoCommit(true);}catch(Exception e){}
                }and the exception is
    Caused by: java.sql.SQLException: Incorrect arguments to mysql_stmt_execute

  • Memory problems with PreparedStatements

    Driver: 9.0.1 JDBC Thin
    I am having memory problems using "PreparedStatement" via jdbc.
    After profiling our application, we found that a large number oracle.jdbc.ttc7.TTCItem objects were being created, but not released, even though we were "closing" the ResultSets of a prepared statements.
    Tracing through the application, it appears that most of these TTCItem objects are created when the statement is executed (not when prepared), therefore I would have assumed that they would be released when the ResultSet is close, but this does not seem to be the case.
    We tend to have a large number of PreparedStatement objects in use (over 100, most with closed ResultSets) and find that our application is using huge amounts of memory when compared to using the same code, but closing the PreparedStatement at the same time as closing the ResultSet.
    Has anyone else found similar problems? If so, does anyone have a work-around or know if this is something that Oracle is looking at fixing?
    Thanks
    Bruce Crosgrove

    From your mail, it is not very clear:
    a) whether your session is an HTTPSession or an application defined
    session.
    b) What is meant by saying: JSP/Servlet is growing.
    However, some pointers:
    a) Are there any timeouts associated with session.
    b) Try to profile your code to see what is causing the memory leak.
    c) Are there references to stale data in your application code.
    Marilla Bax wrote:
    hi,
    we have some memory - problems with the WebLogic Application Server
    4.5.1 on Sun Solaris
    In our Customer Projects we are working with EJB's. for each customer
    transaction we create a session to the weblogic application server.
    now there are some urgent problems with the java process on the server.
    for each session there were allocated 200 - 500 kb memory, within a day
    the JSP process on our server is growing for each session and don't
    reallocate the reserved memory for the old session. as a work around we
    now restart the server every night.
    How can we solve this problem ?? Is it a problem with the operating
    system or the application server or the EJB's ?? Do you have problems
    like this before ?
    greetings from germany,

  • Oracle 9i and PreparedStatement Date Problem

    Hi, I am working with Oracle 9i and it's version of the classes12.zip driver and I am having difficulties in storing a date value using a PreparedStatement. I only care about the date, but I have tried going the Timestamp route as well and get the same results.
    The PreparedStatement's parameters are being set successfully (using setDate or setTimestamp) but when the executeUpdate method is invoked, the process hangs. If I remove the Date (or Timestamp) from the insert, all works as expected.
    Has anyone else came across this problem and if so, how did you get around this?
    Thanks!
    -Brian

    That certainly hasn't happened with any other database including Oracle 8.
    Perhaps you might want to take another look at your code to make sure that it really isn't hanging but instead appears to do so when an exception occurs.

  • Weblogic JTA timeout and PreparedStatement cache problem (Closed Statement)

    Hello,
    I am facing up a problem using a Weblogic connection pool with a PreparedStatement.
    Here is the environement :
    - Weblogic application server 10.3
    - JDBC connection pool with Oracle Thin driver (from server library) - all parameters by default i.e. StatementCache size = 10
    - JTA transaction timeout = 30s
    The problem is : if a prepared statement ends because of a JTA timeout, I receive the following stack exception/ stack trace
    java.sql.SQLException: The transaction is no longer active - status: 'Rolling Back. [Reason=weblogic.transaction.internal.TimedOutException: Transaction timed out after 33 seconds
    BEA1-000D8AE7230EFAA3EDC9]'. No further JDBC access is allowed within this transaction.
    at weblogic.jdbc.wrapper.JTSConnection.checkIfRolledBack(JTSConnection.java:178)
    at weblogic.jdbc.wrapper.JTSConnection.checkConnection(JTSConnection.java:188)
    at weblogic.jdbc.wrapper.Connection.preInvocationHandler(Connection.java:92)
    at weblogic.jdbc.wrapper.Connection.clearCachedStatement(Connection.java:814)
    at weblogic.jdbc.wrapper.PreparedStatement.clearCachedStatement(PreparedStatement.java:1357)
    and then, if we try to re-execute immediately the same operation (*same statement* but new request, new thread, new JTA transaction ...) we receive without delay the following exception :
    java.sql.SQLException: Closed Statement
    at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
    at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:112)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:173)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:229)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:403)
    It seems like a bug in the caching mechanism of Weblogic, the 1st stack trace shows method from the statement cache implementation, I presume weblogic is trying the clear the statement from the cache after the iniitial TimedOutException (SQLException), but as the JDBC connection is unusable at this point, the clearing fails and the statement remains in the cache but is physically closed by JDBC.
    1st question, why weblogic does need to call JTSConnection.checkConnection() for clearing a statement from its internal cache, it is a pure java memory operation isnt'it ?
    2nd question : How to solve the problem without setting the StatementCache size to 0 (I tried, it solves the problem)? I don't want to disable completely the Weblogic statement caching, I have a small PreparedStatement called very frequently.
    Thanks for any help

    The main issue is that the transactional context that is supposed to underlay the JDBC code being executed,
    has gone away. Indeed, any DBMS changes that may have been made by your code so far, have been rolled
    back and are gone. Your code should not be trying to continue JDBC as normal, and WebLogic is trying to stop
    you. The control flow should go back up to the location where the transaction was initiated, so as to restart from
    the beginning if that is what is desired, including getting a new JDBC connection and remaking all the statements
    etc.
    HTH,
    Joe
    Edited by: Joe Weinstein on Dec 3, 2010 9:12 AM

  • Problems with PreparedStatement when select restrict are byte params

    Hi,
    i have a problem trying to select information when the "select" has a byte restrict.
    The table in database is:
    CREATE TABLE `positions` (
    `PKID` int(10) unsigned NOT NULL auto_increment,
    `POSCODE` varbinary(30) NOT NULL,
    `ISWTURN` binary(1) NOT NULL,
    `QTT_GAMES` int(10) unsigned NOT NULL default '1',
    PRIMARY KEY (`PKID`),
    UNIQUE KEY `UNIQ_POS` (`POSCODE`,`ISWTURN`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    And the test code to get the qtt_games is :
    conn = DriverManager.getConnection (url,user,pwd);
    byte bcode[] = poscode.getByteArrayCode();
    // bcode is inserted ok in another preparedstatement...
    String query = "SELECT qtt_games FROM positions "+
    "WHERE poscode=? and iswturn=?";
    PreparedStatement pstmt = conn.prepareStatement(query);
    pstmt.setBytes (1,bcode);
    pstmt.setByte (2,poscode.getIsWhiteTurn()); //it returns a byte
    ResultSet rs = pstmt.executeQuery (query);
    When pstmt.executeQuery is reached, it's thrown the exception:
    com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '=? and iswturn=?' at line 1
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1573)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1665)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3170)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3099)
    at com.mysql.jdbc.Statement.execute(Statement.java:695)
    at app.server.bbdd.MYSQLBDManager.getGamesBasicInfo(MYSQLBDManager.java:942)
    at app.server.bbdd.MYSQLBDManager.main(MYSQLBDManager.java:1068)
    Can anybody tell me what's wrong?? I think the query is ok, but don't know what's happening with this...
    Lots of thanks.

    Hi,
    sorry, i know i've post this same message by error in "new to java" thread.... (i'm new in the forum... can i delete the wrong comment??)
    The SQLState is 42000 (syntax error), but it doesn't give me much information because i had already searched in google why can be the cause of it, but there are only a few comments about problems like this, without a solution...
    The column poscode in the table positions contains an array of bytes that codify a position in a chess board. I've to use this in the WHERE clause because i'm developing a chess game consulting project where there are millions of different positions and i've to get the games that have the same position in it's position history.
    The code to insert the positions is:
    query = "INSERT INTO positions VALUES "+
         "(null,?,?,default) "+
         "ON DUPLICATE KEY UPDATE qtt_games=qtt_games+1";
    pstmt = conn.prepareStatement(query,Statement.RETURN_GENERATED_KEYS);
    pstmt.setBytes(1,bcode);
    pstmt.setByte(2,poscode.getIsWhiteTurn());
    pstmt.executeUpdate();
    which works ok and positions can be seen from mysql browser, but i can't select them using the PreparedStatement..
    I have been searching a lot of information about this problem with no results... this is the why i posted this...
    Any help will be useful, thanks.

  • Problems with PreparedStatement and MySQL selecting bytes

    Hi,
    i have a problem trying to select information when the "select" has a byte restrict.
    The table in database is:
    CREATE TABLE `positions` (
    `PKID` int(10) unsigned NOT NULL auto_increment,
    `POSCODE` varbinary(30) NOT NULL,
    `ISWTURN` binary(1) NOT NULL,
    `QTT_GAMES` int(10) unsigned NOT NULL default '1',
    PRIMARY KEY (`PKID`),
    UNIQUE KEY `UNIQ_POS` (`POSCODE`,`ISWTURN`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    And the test code to get the qtt_games is :
    conn = DriverManager.getConnection (url,user,pwd);
    byte bcode[] = poscode.getByteArrayCode();
    // bcode is inserted ok in another preparedstatement...
    String query = "SELECT qtt_games FROM positions "+
         "WHERE poscode=? and iswturn=?";
    PreparedStatement pstmt = conn.prepareStatement(query);
    pstmt.setBytes (1,bcode);
    pstmt.setByte (2,poscode.getIsWhiteTurn()); //it returns a byte
    ResultSet rs = pstmt.executeQuery (query);
    When pstmt.executeQuery is reached, it's thrown the exception:
    com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '=? and iswturn=?' at line 1
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1573)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1665)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3170)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3099)
    at com.mysql.jdbc.Statement.execute(Statement.java:695)
    at app.server.bbdd.MYSQLBDManager.getGamesBasicInfo(MYSQLBDManager.java:942)
    at app.server.bbdd.MYSQLBDManager.main(MYSQLBDManager.java:1068)
    Can anybody tell me what's wrong?? I think the query is ok, but don't know what's happening with this...
    Lots of thanks.

    Don't cross-post, it's considered rude:
    http://forum.java.sun.com/thread.jspa?threadID=5122604&messageID=9430056#9430056
    http://forum.java.sun.com/thread.jspa?threadID=5122603&messageID=9430050#9430050
    One to a customer, please.
    %

  • Oracle 10G Java PreparedStatement.setString problem

    I am using jboss application server on a windows XP operating system. I installed Oracle 10G production release and am using the jdk 1.4.2.
    When I do a preparedStatment.setString method call to bind the code it does not appear to be binding the variable correctly. I don't get any exceptions it just returns nothing in the resultset. It's like it's binding it but not correctly so it distorts the query results.
    I read the 10G known bug list and found something stating this:
    * If the database character set is AL32UTF8, you may see errors
    under the following circumstances:
    - accessing LONG and VARCHAR2 datatypes.
    - binding data with setString() and setCharacterStream().
    I then tried preparedStatement.setInt to see if this worked and it does without a problem. It appears to be the setString method. I then tried doign a workaround and using setObject instead. Also does not work. I checked the database character set and it appears I have this:
    NLS_CHARACTERSET
    WE8MSWIN1252
    NLS_NCHAR_CHARACTERSET
    AL16UTF16
    I'm very confused as this is a big problem if I can't use the setString to bind. Has anyone else found this to be the case. Any workarounds or advice for fixing?
    Thanks in advance!
    L

    Character interpretation is up to the client- as long as the database character set can handle a specific character, the client software is responsible for accepting '<char code>' from the database and rendering it as the proper '<char>'. If the client doesn't know the code point '<char code>' you get the inverted question mark.
    Are you running the WE (Western European) charset or did you install the Universal one? A quick way to check that is to do a control file trace backup and check the create controlfile SQL generated ...
    $ sqlplus /nolog;
    show parameter user_dump;
    ... --- s.b. ...admin/XE/udump
    alter database backup controlfile to trace;
    And check the ...udump directory, view the latest .trc file- CREATE CONTROLFILE ... ; if its universal should be:
    CHARACTER SET AL32UTF8
    ;

  • Performance Problem - MS SQL 2K and PreparedStatement

    Hi all
    I am using MS SQL 2k and used PreparedStatement to retrieve data. There is strange and serious performance problem when the PreparedStatement contains "?" and using PreparedStatement.setX() functions to set its value. I have performed the test with the following code.
    for (int i = 0; i < 10; i ++) {
    try {
    con = DBConnection.getInstance();
    statement = con.prepareStatement("SELECT * FROM cardno WHERE car_no = '" + cardNo + "'");
    // statement = con.prepareStatement("SELECT * FROM cardno WHERE car_no = ?");
    // statement.setString(1, cardNo);
    rs = statement.executeQuery();
    if (rs.next()) {
    catch(SQLException e) {
    e.printStackTrace();
    finally {
    try {
    rs.close();
    statement.close();
    catch(SQLException e) {
    e.printStackTrace();
    Iteration Time (ms)
    1 961
    10 1061
    200 1803
    for (int i = 0; i < 10; i ++) {
    try {
    con = DBConnection.getInstance();
    // statement = con.prepareStatement("SELECT * FROM cardno WHERE car_no = '" + cardNo + "'");
    statement = con.prepareStatement("SELECT * FROM cardno WHERE car_no = ?");
    statement.setString(1, cardNo);
    rs = statement.executeQuery();
    if (rs.next()) {
    catch(SQLException e) {
    e.printStackTrace();
    finally {
    try {
    rs.close();
    statement.close();
    catch(SQLException e) {
    e.printStackTrace();
    Iteration Time (ms)
    1 1171
    10 2754
    100 18817
    200 36443
    The above test is performed with DataDirect JDBC 3.0 driver. The one uses ? and setString functions take much longer to execute, which supposed to be faster because of precompilation of the statement.
    I have tried different drivers - the one provided by MS, data direct and Sprinta JDBC drivers but all suffer the same problem in different extent. So, I am wondering if MS SQL doesn't support for precompiled statement and no matter what JDBC driver I used I am still having the performance problem. If so, many O/R mappings cannot be used because I believe most of them if not all use the precompiled statement.
    Best regards
    Edmond

    Edmond,
    Most JDBC drivers for MS SQL (and I think this includes all the drivers you tested) use sp_executesql to execute PreparedStatements. This is a pretty good solution as the driver doesn't have to keep any information about the PreparedStatement locally, the server takes care of all the precompiling and caching. And if the statement isn't already precompiled, this is also taken care of transparently by SQL Server.
    The problem with this approach is that all names in the query must be fully qualified. This means that the driver has to parse the query you are submitting and make all names fully qualified (by prepending a db name and schema). This is why creating a PreparedStatement takes so much using these drivers (and why it does so every time you create it, even though it's the same PreparedStatement).
    However, the speed advantage of PreparedStatements only becomes visible if you reuse the statement a lot of times.
    As about why the PreparedStatement with no placeholder is much faster, I think is because of internal optimisations (maybe the statement is run as a plain statement (?) ).
    As a conclusion, if you can reuse the same PreparedStatement, then the performance hit is not so high. Just ignore it. However, if the PreparedStatement is created each time and only used a few times, then you might have a performance issue. In this case I would recommend you try out the jTDS driver ( http://jtds.sourceforge.net ), which uses a completely different approach: temporary stored procedures are created for PreparedStatements. This means that no parsing is done by the driver and PreparedStatement caching is possible (i.e. the next time you are preparing the same statement it will take much less as the previously submitted procedure will be reused).
    Alin.

Maybe you are looking for

  • UDP FLOODING and NON-FUNCTIONAL INBOUND LOG

    Hello, I have been using Linksys Routers since 1998, IIRC. I just bought a new "Cisco" (LINKSYS) E1200 and the INBOUND log does not work, even after activation the log function in the "Administration" area. The OUTBOUND log works. Also, my desktop wo

  • Condition in Order by clause?

    hi, my db version is,      Oracle9i Enterprise Edition Release 9.2.0.8.0 - Production     Im having a query like this,     select a,b,c,d,sum(e) from f group by a,b,c,d order by a,b,c,d     Now if the value of the a is 1 i want to have the result of

  • System center sql 2012 remote or local install

    Guys I'm testing System Center 2012 R2 right now I plan on installing configuration manager for starters. I would like to ask you guys did you install your sql server instance locally for System Center or do you have a remote SQL server installation

  • CC 5.X Alerts Functionality - Q's

    Please help wth the below questions regarding Alerts in CC 5.2 - For Conflicting alerts, we are receiving alerts even if the conflicting TCodes are executed 6 months apart, is there a parameter to fix this to report an alert if executed within a mont

  • Converting layers to table - Mine won't work!

    Hi, In Dreamweaver I first created a template of my website. Using the template I then wanted to create my very first official home page, called index.htm. This is the problem i've got; when I open a blank white Dreamweaver page i go to 'File > New f