Setting date to null in prepared statement

Can anyone tell me how to set a date in Oracle to null using prepared statements.
prepared.setDate

Have you tried using the setNull parameter? The following should work for you. (I haven't tested it.)
prepared.setNull(1, Types.DATE);

Similar Messages

  • Null in prepares statement

    Hi All,
    I had the following code but it shows me an errors
    Will you please find out where i made mistake.
    Is it possible to use nulls in prepared statement as below.
    String result=null;
                   int i=null;
                   int j=null;
    try
                        String query= "Select TO_NUMBER(pk2_value) organization_id
                             , TO_NUMBER(pk1_value) item_id
                             FROM ENG_CHANGE_SUBJECTS
                             WHERE pk1_value IS NOT NULL
                             AND pk2_value IS NOT NULL
                             AND change_line_id IS NULL
                                  AND entity_name like 'EGO_ITEM'
                             AND change_id = ?";
                   PreparedStatement pstmt=oaapplicationmodule.getOADBTransaction().getJdbcConnection().prepareStatement(query);
                   ResultSet rs=pstmt.executeQuery();
                   while(rs.next())
                   i=rs.getInt("item_id");
                   j= rs.getInt("organization_id");
                   result+=i+"\t\t"+j+"\n";
                   catch(SQLException sqlexception)
                   sqlexception.printStackTrace();
    Regards
    Zaheer

    i=rs.getInt("item_id");
    j= rs.getInt("organization_id");
    this is not the way
    try this
    i=rs.getInt(1)
    j= rs.getInt(2);
    Also you are not setting the value for "change_id = ?" in your prepare statement before executing the query
    like
    pstmt.setLong(1, "value to be set");
    pstmt.executeQuery();

  • Date objects and prepared statements

    Hi, I am trying to parse a String into a Date object with format "dd/MM/yyyy hh/mm/ss". Anyway, i have a method in a separate class which reads in a String and converts it to a formatted Date object.
    static public Date convertToDate(String t) throws ParseException {
    Date dd = new Date();
    ParsePosition p = new ParsePosition(0);
    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
    //y, M, etc are retrieved as substrings of String t. I know these methods are deprecated as well
    dd.setYear(y);
    dd.setMonth(M);
    dd.setDate(d);
    dd.setHours(h);
    dd.setMinutes(m);
    dd.setSeconds(s);
    String formattedDate = formatter.format(dd);
    Date theDate = formatter.parse(formattedDate);
    return theDate;
    Anyway, I am trying to use this in an SQL statement because I am using an Access DB which has a field of Date/Time value. Is this correct to use a Date object then? I have a prepared statement -
    PreparedStatement query = connection.prepareStatement(
    "SELECT FText FROM wnioutput WHERE Id = ? AND Section = ? AND Start = " +
    "? AND Field = ?");
    //start is the Date object returned from the previous method in a separate class
    query.setInt(1, id);
    query.setInt(2, section);
    query.setDate(3, formattedStart); - with this part, i get a setDate method not found, or something
    query.setString(4, ch);
    Can anybody tell me what the problem is? I know there are Date objects of java.util and java.sql. Should i be using an sql Date object? And if so, how, and where do I do this? Thank you!

    ok, i just tried
    query.setTimestamp(3, new java.sql.Timestamp(formattedStart.getTime()));
    where formattedStart is a java.util.Date object
    and I get the following error message -
    Error occured in getting endDateAndTime: java.sql.SQLException: Exception in databaseDisplay: the error message is:java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression.
    java.lang.NullPointerException
    where endDateAndTime is
    // takes in the startDateAndTime as a formatted String (before it is converted into a Date object)
    public String getEndTime(int s, int ID, String stDateAndTime) {
    String end = null;
    gui g = new gui();
    try {
    String sql = "SELECT End FROM wnioutput WHERE Id = " + ID +
    " AND Section = " + s +
    " AND Start = '" + stDateAndTime + "' AND Field = 'Wind50m'";
    ResultSet result = g.queryDatabase(sql);
    if (result.next())
    end = result.getString("End");
    } catch (SQLException sqlex) {
    System.out.println("Error occured in getting endDateAndTime: " + sqlex.toString());
    return end;
    Although this method worked fine before. So the error is in setting the date object in the prepared statement. Anymore suggestions??

  • SetTimestamp on prepared statement returns SQLException

    I have to synchronize data between our new web app and a legacy app. The legacy app can't handle null dates in SQL so all blank dates are saved as 1753-01-01 00:00:00.000.
    I have (relevant parts):
    ps.setTimestamp(i++, safeTime(rs.getTimestamp("DOT"))); private Timestamp safeTime(Timestamp t) { Calendar noCal = Calendar.getInstance(); noCal.clear(); noCal.set(1753, Calendar.JANUARY, 1); noTime = new Timestamp(noCal.getTimeInMillis()); if (t == null) return noTime; return t; }
    It throws a SQLException error Only dates between January 1, 1753 and December 31, 9999 are accepted. I checked the field for DOT and it is null. noTime on this record returns a timestamp of -6847804800000. safeTime printed to the console returns 1753-01-01 00:00:00.0. I'm at a loss. I'm trying to set a timestamp in the prepared statement of January 1, 1753, but it's telling me it's outside of the date range??? What could be wrong?
    Thanks

    Hmmm, version, not sure how to find that out. Server.xml has:
    <Resource auth="Container" 
           driverClassName="net.sourceforge.jtds.jdbc.Driver" 
           maxActive="100" maxIdle="30" maxWait="10000" name="jdbc/Desk" password="xxxxxx" removeAbandoned="true" removeAbandonedTimeout="30" type="javax.sql.DataSource" 
           url="jdbc:jtds:sqlserver://192.168.123.2:1433" username="xxxxx"/> Stack:
    java.sql.SQLException: Only dates between January 1, 1753 and December 31, 9999 are accepted.
         at net.sourceforge.jtds.jdbc.DateTime.packDate(DateTime.java:300)
         at net.sourceforge.jtds.jdbc.DateTime.<init>(DateTime.java:121)
         at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.setParameter(JtdsPreparedStatement.java:445)
         at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.setTimestamp(JtdsPreparedStatement.java:841)
         at org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.setTimestamp(DelegatingPreparedStatement.java:143)
         at desk.desk.DataSynchAction.updateEmployee(DataSynchAction.java:888)
         at desk.desk.DataSynchAction.updateEmployees(DataSynchAction.java:785)
         at desk.desk.DataSynchAction.execute(DataSynchAction.java:103)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at com.opensymphony.xwork.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:364)
         at com.opensymphony.xwork.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:216)
         at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:190)
         at com.opensymphony.xwork.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:168)
         at com.opensymphony.xwork.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86)
         at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:188)
         at com.opensymphony.xwork.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:115)
         at com.opensymphony.xwork.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86)
         at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:188)
         at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:31)
         at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:188)
         at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:31)
         at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:188)
         at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:31)
         at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:188)
         at com.opensymphony.webwork.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:171)
         at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:188)
         at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:31)
         at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:188)
         at com.opensymphony.webwork.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:147)
         at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:188)
         at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:31)
         at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:188)
         at com.opensymphony.xwork.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:151)
         at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:188)
         at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:31)
         at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:188)
         at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:31)
         at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:188)
         at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:31)
         at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:188)
         at com.opensymphony.xwork.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:186)
         at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:188)
         at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:31)
         at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:188)
         at desk.desk.SecurityCheck.intercept(SecurityCheck.java:29)
         at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:188)
         at com.opensymphony.xwork.DefaultActionProxy.execute(DefaultActionProxy.java:113)
         at com.opensymphony.webwork.dispatcher.DispatcherUtils.serviceAction(DispatcherUtils.java:225)
         at com.opensymphony.webwork.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:202)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
         at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:525)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)
         at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
         at java.lang.Thread.run(Unknown Source)If I set the timestamp to 0, I would still need to set it to 01/01/1753 in the legacy db.

  • Required Prepared Statement help

    Consider the following query
    select col2, col3
    from table1
    where col1 = ?
    I can set the bindings for the prepared statement as pStmt.setString(1, value);
    but sometimes I need all the rows in the table therefore the query would be like
    select col2, col3
    from table1
    where col1 = col1
    I would like to set the first query's bindings for the prepared statement to execute like the second one.
    Please do not ask me to create two different queries. I know it is possible to do it and I would appreciate if you can guide me as to how to set the bindings. Thanks,

    Adam Martin wrote:
    Sorry, you cannot treat a bind variable like a bind some of the time and literal SQL text the other part of the time.
    How about something like this:
    select col2, col3
    from table1
    where col1 between ? and ?When you want a specific value, you can say "between 23 and 23" and when you want all values, you can put extremes in like "between -999999 and 999999" so that all rows a returned.
    This is not to say that this is a great approach, but it seems like it would technically allow you to do what you wanted.This is an EXCELLENT approach to confuse the optimizer & produce poor performance.
    I suspect that using the same EXPLAIN PLAN to bring back 1 or and bring back all rows;
    will be suboptimal for a subset of all executions.

  • Prepared Statement - updating problem

    Hello all together!
    I've a problem and I hope somebody could help me out of misery!
    I have created a table and now I want to update a special cell and my aim is to use prepared statements
    I have generated it in the form mentioned below:
    public void setValueAt(Object newValue, int row, int col) {
    try {
    stmtPrep.setString(1, getColumnName(col)); // this should initalize the column I want to update
    stmtPrep.setObject(2, newValue); //this is the new value which should be set
    rowElements = getElementsOfRow(row);
    stmtPrep.setInt(3, (Integer.parseInt((String)rowElements[0]))); //this is my primary key
    stmtPrep.executeUpdate();
    stmtPrep.clearParameters();
    rs.updateRow();
    } catch (SQLException e) {e.printStackTrace(); }
    My SQL-Statement looks like this:
    private String queryPrep = "update Buch set ? = ? where isbn = ?";
    My problem is that column is not set.... am I not allowed to set column name in the prepared statement??
    how do I manage to show my changes in a master/detail implementation?
    anybode a clue????

    Hi majandrah,
    My SQL-Statement looks like this:
    private String queryPrep = "update Buch set ? = ?
    where isbn = ?";Sorry, not allowed.
    My problem is that column is not set.... am I not
    allowed to set column name in the prepared
    statement??No, you are not. Parameters can only be used for literal values -- not for names of columns , tables, etc.
    how do I manage to show my changes in a master/detail
    implementation?
    anybode a clue????I suggest using the java.text.MessageFormat class, like so:
    MessageFormat queryPrep = new MessageFormat("update BUCH set {0} = ? where ISBN = ?");
    String query = queryPrep.format(String[]{getColumnName(col)});
    // Now use your (posted) code, starting at line...
    stmtPrep.setObject(2, newValue);Good Luck,
    Avi.

  • Resultset from a batch select using prepared statement

    Hi,
    Is it possible to add results of batch execute of select statements and retrieve the result set ..
    I am running select statement in a batch mode setting in value for a column.I add this to a prepared batch.
    I would like to get the reults as a batch and spin through the result set like a r.next(). Is this possible ?
    I have given the code below
    sql = "select ordervalue , orderdate from discreet_orders "+
    "where order_no = ? ";
    dbObject.prepareStatement(sql);
    dbObject.prepareStatement(sql);
    for (int i=0; i < orderNoVect.size(); i++) {
    dbObject.setString(1,(String)scnV.elementAt(i));
    dbObject.addBatchPrepared();
    r = dbObject.execPrepared();
    dbObject.clearBatchPrepared();
    I would like to do a r.getNext() process the values form the resultset.
    Is this possible ? If not is there an other way to do it ?
    Thanks
    Arnold

    Olek wrote:
    hi
    Is there a way do a batch update using prepared statement?
    I don't want to insert every row in a single query...
    regards,
    OlekPossibly the confusion here stems from the existence of two addBatch methods in PreparedStatement.
    addBatch(String sql)inherited from Statement adds a new query to the batch of SQL statements for the statement. However you don't want to use this with PreparedStatements Instead you want
    addBatch()which adds the current set of parameters to the prepared statements batch of commands.
    In this scenario you prepare your query (insert statement) and then call setXXX(x,y) for each parameter and then addBatch for each tuple. Then call executeBatch to execute all the queries based on your batched parameters.
    If this didn't answer your question I don't know what your question is exactly. I would add that you probably want to set a "reasonable" size on your batches and break them into smaller batches as is reasonable. Mainly because the implementation of batched PreparedStatements widely varies depending on the database and driver, thus there are certainly scenarios where given enough batched parameters you could have various unpleasant things visited upon your program. Like terminal slowness, running out of memory, etc.

  • ArrayIndexOutOfBoundsException when setting a date in a prepared statement

    Hi,
    was wondering if anyone could help. I have a prepared statement, with two "variables" in it. I need to set the first of these to a string (using setString(1, "string)
    and the second to a date, using setDate(2, SQLDate)
    My SQL date is a valid date ass I've run a debugger and checked, but everytime setDate is called an Array Out Of Bound Exception is thrown. Can anyone shed any light on this as I'm rather confused as to why this is happening!
    Thanks in advance

    I havent got a small runnable example to hand, but taking an excert from my code I have:
    for (int i = 0; i < this.columnNames.size();i++)
    singleDateEventFlagSingleArea.setString(1, newAreaName);
    singleDateEventFlagSingleArea.setDate(2, Date.valueOf((String) this.columnNames.get(i)));
    eventFlagsResult = singleDateEventFlagSingleArea.executeQuery()
    }newAreaName is a argument passed to the method. columnNames is a vector of dates/strings, which I parse back into a date to pass to the setDate method
    Where the value of the date in the statement is changed to a preset value each iteration.
    The exception stack I'm getting is:
    exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1
         at oracle.jdbc.dbaccess.DBDataSetImpl._getDBItem(DBDataSetImpl.java:378)
         at oracle.jdbc.dbaccess.DBDataSetImpl._createOrGetDBItem(DBDataSetImpl.java:781)
         at oracle.jdbc.dbaccess.DBDataSetImpl.setBytesBindItem(DBDataSetImpl.java:2399)
         at oracle.jdbc.driver.OraclePreparedStatement.setItem(OraclePreparedStatement.java:1134)
         at oracle.jdbc.driver.OraclePreparedStatement.setDate(OraclePreparedStatement.java:2223)
         at treeTableVersion2.TreeTable.updateValuesSingleDateSingleArea(TreeTable.java:393)
         at treeTableVersion2.TestWindow.actionPerformed(TestWindow.java:394)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
         at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:234)
         at java.awt.Component.processMouseEvent(Component.java:5488)
         at javax.swing.JComponent.processMouseEvent(JComponent.java:3126)
         at java.awt.Component.processEvent(Component.java:5253)
         at java.awt.Container.processEvent(Container.java:1966)
         at java.awt.Component.dispatchEventImpl(Component.java:3955)
         at java.awt.Container.dispatchEventImpl(Container.java:2024)
         at java.awt.Component.dispatchEvent(Component.java:3803)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
         at java.awt.Container.dispatchEventImpl(Container.java:2010)
         at java.awt.Window.dispatchEventImpl(Window.java:1774)
         at java.awt.Component.dispatchEvent(Component.java:3803)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)Although I think a lot of that is because the process is called by a button press.
    The sql statement thats causing the problem is:
    select h.areaname,
           e.code,
           e.descript,
           ec.date_raised,
           ec.date_progressing,
           ec.date_completed
      from hareas h, evt_type e, evt_core ec
    where h.areaname = ?
       and e.evt_type_id = ec.evt_type_id
       and (h.nblink = ec.area1_nblink or h.nblink = ec.area2_nblink)
       and ec.date_raised = ?
    group by h.areaname,
              e.code,
              e.descript,
              ec.date_raised,
              ec.date_progressing,
              ec.date_completed
    order by h.areanameThanks for your help

  • Setting date in prepared statement

    I am using
    preparesStatement.setDate(param1,findAuditSearchDTO.getStgAuditGeneral().getAuditBeginDate());
    I am wondering setting date this way will slow down the query?
    should I use preparesStatement.setString where I can call to_date function or the above code will work fine and not make any difference in performance ?

    user11138293 wrote:
    I am using
    preparesStatement.setDate(param1,findAuditSearchDTO.getStgAuditGeneral().getAuditBeginDate());
    I am wondering setting date this way will slow down the query? No. And even if it did, it would still be the right way to do it. The main point of using PreparedStatement is so that you can use the correct types in your Java code and don't have to worry about formatting and such.
    As far as performance is concerned, any difference introduced by type conversion will be minuscule compared to roundtrip I/O between you and the DB and any disk I/O the DB needs to do. And of course, if it's a DATE column on the DB (which it had better be, if it's representing a date), then the DB would just have to convert the string to a date anyway.
    Focus on good design, and on using data structures, algorithms, classes, and methods, that are appropriate to what you're trying to do and that lead to easy-to-understand code.

  • How do I handle NULL returns from prepared statement?

    Thanks in advance to all those who respond. As a beginner with Java/JSP/JDBC, I need all the help I can get!
    Here's the problem...
    I'm using a prepared statement in JSP to query a MySQL database.
    If there is a value to return, everything works properly.
    If the query returns a NULL (empty set) value, I get the following error:
    javax.servlet.ServletException: Before start of result set
    Here's the code (no negative comments please...I know I'm violating some conventions! I'll restructure it later. Right now I just need help with handling the NULL case):
    <%
    Driver DriverAppt = (Driver)Class.forName(MM_test_DRIVER).newInstance();
    Connection ConnAppt = DriverManager.getConnection(MM_test_STRING,MM_test_USERNAME,MM_test_PASSWORD);PreparedStatement StatementAppt = ConnAppt.prepareStatement("SELECT lastname FROM appts_pid1 WHERE user_id = " + Recordset1__MMColParam + " AND year = " + yy + " AND month = '" + months[mm] + "' AND date = " + dates[dd] + " AND appttime = '16:15:00'");
    ResultSet Appt = StatementAppt.executeQuery();
    boolean Appt_isEmpty = !Appt.first();
    boolean Appt_hasData = !Appt_isEmpty;
    Object Appt_data;
    int Appt_numRows = 0;
    %>
    Thanks for the help!!!

    I think I have a better handle on what's occurring here. To cut to the heart of the problem, I'm going to give a very simple example that illustrates what type of error handling I need.
    HERE'S THE EXAMPLE:
    Let's say that I have a database of users. There are only two columns in the database: user_id and lastname. There are only 2 users, user_id "1" has lastname "Jones" and user_id "2" has lastname "Smith".
    I built a very simple web interface that let's a user enter a number to see if there's a lastname associated with that record. The user has no way of knowing if the user_id exists or not, so they may or may not enter a valid number.
    If the user enters a valid user_id (in this case "1" or "2"), then the correct lastname is displayed. If the user enters an invalid user_id (in this case, anything other than "1" or "2") then I get the same "Before start of result set" error that I'm getting in my real application.
    So, the question is: WHERE IN THIS CODE WOULD I HANDLE THE RETURN OF AN EMPTY SET?
    The goal here is to have the sentence say "The user's lastname is .", basically returning null. If there has to be a value, then have the last sentence say "The user's lastname is unknown."
    If you can solve this simple example, you'll have also solved the problem with my main application!!!! :-)
    Here's the example code:
    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
    <%@ include file="Connections/example.jsp" %>
    <%
    String Recordset1__MMColParam = "1";
    if (request.getParameter("user_id") !=null) {Recordset1__MMColParam = (String)request.getParameter("user_id");}
    %>
    <%
    Driver DriverRecordset1 = (Driver)Class.forName(MM_example_DRIVER).newInstance();
    Connection ConnRecordset1 = DriverManager.getConnection(MM_example_STRING,MM_example_USERNAME,MM_example_PASSWORD);
    PreparedStatement StatementRecordset1 = ConnRecordset1.prepareStatement("SELECT * FROM test_table WHERE user_id = " + Recordset1__MMColParam + "");
    ResultSet Recordset1 = StatementRecordset1.executeQuery();
    boolean Recordset1_isEmpty = !Recordset1.next();
    boolean Recordset1_hasData = !Recordset1_isEmpty;
    Object Recordset1_data;
    int Recordset1_numRows = 0;
    %>
    <html>
    <head>
    <title>Untitled Document</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    </head>
    <body>
    <form action="test.jsp" method="get" enctype="application/x-www-form-urlencoded" name="form1" target="_self">
    <p> Submit a user id and a lastname will be displayed.</p>
    <p>
    <input type="text" name="user_id">
    <input type="submit" name="" value="Submit">
    </p>
    </form>
    <p>The User's lastname is <%=(((Recordset1_data = Recordset1.getObject("lastname"))==null || Recordset1.wasNull())?"":Recordset1_data)%>.</p>
    </body>
    </html>
    <%
    Recordset1.close();
    StatementRecordset1.close();
    ConnRecordset1.close();
    %>
    A huge "THANK YOU!!!!" to all those who've helped me here!!!

  • Prepared statement - setDate(index, sql.Date, Cal) Help!

    Hi everyone, I'm creating a form to query an Oracle table. I'm setting up the search criteria which includes a start and end date. (in this example I've just used the start date)
    I get all the search parameters into my JSP and I created the following Calendar objects:
    // Calendar creation
    Calendar startCal = Calendar.getInstance();
    startCal.set(start_year, start_month, start_day, start_hour, start_minute);
    Calendar endCal = Calendar.getInstance();
    endCal.set(end_year, end_month, end_day, end_hour, end_minute);
    //define a sql.Date value for start and end date
    java.sql.Date startDate = null;
    java.sql.Date endDate = null;I then create a string that contains my SQL statement:
    String sqlStmt = "select dateValue, value3 from someTable where dateValue >= ? and value2 = ?";In my Prepared Statement I pass in the following information:
    ps = c.prepareStatement(sqlStmt);
    ps.setDate(1, startDate, startCal);
    ps.setString(2, searchValue);My question is the following - I define the hour and minute in my Cal object - will that information get passed into my "startDate" sql.Date object? According to the API it should work (at least that's my understading of it):
    http://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.html#setDate(int,%20java.sql.Date,%20java.util.Calendar)
    My search does not blow up or report any errors but it never finds a match - even when I put in parameters that I know are a match.
    Any feedback is appreciated.

    I think I got it. my java.sql.Date can't be null.
    java.sql.Date startDate = null;
    java.sql.Date endDate = null;needs to be:
    java.util.Date startCalendarDate = startCal.getTime();
    java.util.Date endCalendarDate = endCal.getTime();
    java.sql.Date startDate = new java.sql.Date(startCalendarDate.getTime());
    java.sql.Date endDate = new java.sql.Date(endCalendarDate.getTime());

  • Weblogic generated finder method not setting parameters in prepared statement

    Hi,
    I am using weblogic 6.1 sp2 and have a CMP bean with a finder defined as follows:
    <query>
    <query-method>
    <method-name>findByPcPayclass</method-name>
    <method-params>
    <method-param>java.lang.String</method-param>
    </method-params>
    </query-method>
    <ejb-ql>SELECT DISTINCT OBJECT(p) FROM Payments p, PaymentType
    t WHERE p.paymentType.pcPayClass = '?1'</ejb-ql>
    </query>
    The weblogic generated code follwos:
    public java.util.Collection ejbFindByPcPayclass(java.lang.String param0) throws
    javax.ejb.FinderException
    if(__WL_verbose) {
    Debug.say("called findByPcPayclass");
    java.sql.Connection __WL_con = null;
    java.sql.PreparedStatement __WL_stmt = null;
    java.sql.ResultSet __WL_rs = null;
    __WL_pm.flushModifiedBeans();
    try {
    __WL_con = __WL_pm.getConnection();
    } catch (java.lang.Exception e) {
    __WL_pm.releaseResources(__WL_con, __WL_stmt, __WL_rs);
    throw new javax.ejb.FinderException("Couldn't get connection: " + EOL +
    e.toString() + EOL +
    RDBMSUtils.throwable2StackTrace(e));
    try {
    java.lang.String __WL_query = "SELECT WL0.DEPOSIT_UID, WL0.GLA_ID, WL0.MARKET_CODE,
    WL0.ORIGINAL_PAYMENT_ID, WL0.PAYMENT_ACCT_NUMBER, WL0.PAYMENT_ACK, WL0.PAYMENT_AMOUNT,
    WL0.PAYMENT_CARD_CHECK_NUM, WL0.PAYMENT_CARE_SITE, WL0.PAYMENT_CUST_NAME, WL0.PAYMENT_DESIGNATOR,
    WL0.PAYMENT_EFFECTIVE_DATE, WL0.PAYMENT_ID, WL0.PAYMENT_INV_ID, WL0.PAYMENT_MOBILE_NUMBER,
    WL0.PAYMENT_SPLIT, WL0.PC_PAYCLASS, WL0.PT_UID, WL0.TT_UID FROM payment_type
    WL2, payment_type WL1, payments WL0 WHERE (WL2.PC_PAYCLASS = '?1') AND WL0.PT_UID
    = WL2.PT_UID " + __WL_pm.selectForUpdate();
    if(__WL_verbose) {
    Debug.say("Finder produced statement string " + __WL_query);
    __WL_stmt = __WL_con.prepareStatement(__WL_query);
    // preparedStatementParamIndex reset.
    __WL_rs = __WL_stmt.executeQuery();
    } catch (java.lang.Exception e) {
    __WL_pm.releaseResources(__WL_con, __WL_stmt, __WL_rs);
    throw new javax.ejb.FinderException(
    "Exception in findByPcPayclass while preparing or executing " +
    "statement: '" + __WL_stmt + "'" + EOL +
    e.toString() + EOL +
    RDBMSUtils.throwable2StackTrace(e));
    The parameter is never set in the prepared statement before it executes. This
    causes the finder to return an empty result set. Is this a bug or is there some
    configuration that I missed. I am using ant 1.5 to do the ejbc. the ant target
    follows:
    <target name="ccas.ejbc" depends="ccas.compile, ccas.stage, dd.combine">
    <ejbjar srcdir="${buildClasses}/"
    descriptordir="${buildOutput}/ear_dd"
    basejarname="CCAS"
    flatdestdir="true"
    dependency="full">
    <support dir="${buildClasses}">
    <include name="CCAS/**/*.class"/>
    </support>
    <weblogic destdir="${ear.stage.dir}"
    rebuild="false"
    keepgenerated="true"
    jvmdebuglevel="16">
    <classpath refid="classpath"/>
    <wlclasspath refid="classpath"/>
    </weblogic>
    <include name="ejb-jar.xml"/>
    <exclude name="**/*-weblogic*.xml"/>
    </ejbjar>
    </target>

    replace '?1' with ?1
    "Eugene Stephens" <[email protected]> wrote in message
    news:[email protected]...
    >
    Hi,
    I am using weblogic 6.1 sp2 and have a CMP bean with a finder defined asfollows:
    <query>
    <query-method>
    <method-name>findByPcPayclass</method-name>
    <method-params>
    <method-param>java.lang.String</method-param>
    </method-params>
    </query-method>
    <ejb-ql>SELECT DISTINCT OBJECT(p) FROM Payments p,PaymentType
    t WHERE p.paymentType.pcPayClass = '?1'</ejb-ql>
    </query>
    The weblogic generated code follwos:
    public java.util.Collection ejbFindByPcPayclass(java.lang.String param0)throws
    javax.ejb.FinderException
    if(__WL_verbose) {
    Debug.say("called findByPcPayclass");
    java.sql.Connection __WL_con = null;
    java.sql.PreparedStatement __WL_stmt = null;
    java.sql.ResultSet __WL_rs = null;
    __WL_pm.flushModifiedBeans();
    try {
    __WL_con = __WL_pm.getConnection();
    } catch (java.lang.Exception e) {
    __WL_pm.releaseResources(__WL_con, __WL_stmt, __WL_rs);
    throw new javax.ejb.FinderException("Couldn't get connection: " +EOL +
    e.toString() + EOL +
    RDBMSUtils.throwable2StackTrace(e));
    try {
    java.lang.String __WL_query = "SELECT WL0.DEPOSIT_UID, WL0.GLA_ID,WL0.MARKET_CODE,
    WL0.ORIGINAL_PAYMENT_ID, WL0.PAYMENT_ACCT_NUMBER, WL0.PAYMENT_ACK,WL0.PAYMENT_AMOUNT,
    WL0.PAYMENT_CARD_CHECK_NUM, WL0.PAYMENT_CARE_SITE, WL0.PAYMENT_CUST_NAME,WL0.PAYMENT_DESIGNATOR,
    WL0.PAYMENT_EFFECTIVE_DATE, WL0.PAYMENT_ID, WL0.PAYMENT_INV_ID,WL0.PAYMENT_MOBILE_NUMBER,
    WL0.PAYMENT_SPLIT, WL0.PC_PAYCLASS, WL0.PT_UID, WL0.TT_UID FROMpayment_type
    WL2, payment_type WL1, payments WL0 WHERE (WL2.PC_PAYCLASS = '?1') ANDWL0.PT_UID
    = WL2.PT_UID " + __WL_pm.selectForUpdate();
    if(__WL_verbose) {
    Debug.say("Finder produced statement string " + __WL_query);
    __WL_stmt = __WL_con.prepareStatement(__WL_query);
    // preparedStatementParamIndex reset.
    __WL_rs = __WL_stmt.executeQuery();
    } catch (java.lang.Exception e) {
    __WL_pm.releaseResources(__WL_con, __WL_stmt, __WL_rs);
    throw new javax.ejb.FinderException(
    "Exception in findByPcPayclass while preparing or executing " +
    "statement: '" + __WL_stmt + "'" + EOL +
    e.toString() + EOL +
    RDBMSUtils.throwable2StackTrace(e));
    The parameter is never set in the prepared statement before it executes.This
    causes the finder to return an empty result set. Is this a bug or is theresome
    configuration that I missed. I am using ant 1.5 to do the ejbc. the anttarget
    follows:
    <target name="ccas.ejbc" depends="ccas.compile, ccas.stage,dd.combine">
    <ejbjar srcdir="${buildClasses}/"
    descriptordir="${buildOutput}/ear_dd"
    basejarname="CCAS"
    flatdestdir="true"
    dependency="full">
    <support dir="${buildClasses}">
    <include name="CCAS/**/*.class"/>
    </support>
    <weblogic destdir="${ear.stage.dir}"
    rebuild="false"
    keepgenerated="true"
    jvmdebuglevel="16">
    <classpath refid="classpath"/>
    <wlclasspath refid="classpath"/>
    </weblogic>
    <include name="ejb-jar.xml"/>
    <exclude name="**/*-weblogic*.xml"/>
    </ejbjar>
    </target>

  • Help with streaming result sets and prepared statements

    hi all
    I create a callable statement that is capable of streaming.
    statement = myConn2.prepareCall("{call graphProc(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}",java.sql.ResultSet.TYPE_FORWARD_ONLY,
    java.sql.ResultSet.CONCUR_READ_ONLY);
    statementOne.setFetchSize(Integer.MIN_VALUE);
    the class that contains the query is instantiated 6 times the first class streams the results beautifully and then when the second
    rs = DatabaseConnect.statementOne.executeQuery();
    is executed I get the following error
    java.sql.SQLException: Can not use streaming results with multiple result statements
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:910)
    at com.mysql.jdbc.MysqlIO.readAllResults(MysqlIO.java:1370)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1688)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3031)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:943)
    at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1049)
    at com.mysql.jdbc.CallableStatement.executeQuery(CallableStatement.java:589)
    the 6 instances are not threaded and the result set is closed before the next query executes is there a solution to this problem it would be greatly appreciated
    thanks a lot
    Brian

    Database resources should have the narrowed scope
    possible. I don't think it's a good idea to use a
    ResultSet in a UI to generate a graph. Load the data
    into an object or data structure inside the method
    that's doing the query and close the ResultSet in a
    finally block. Use the data structure to generate
    the graph.
    It's an example of MVC and layering.
    Ok that is my bad for not elaborating on the finer points sorry, the results are not directly streamed into the graphs from the result set. and are processed in another object and then plotted from there.
    with regards to your statement in the beginning I would like to ask if you think it at least a viable option to create six connections. with that said would you be able to give estimated users using the six connections under full usage.
    just a few thoughts that I want to
    bounce off you if you don't mind. Closing the
    statement would defeat the object of of having a
    callable statement How so? I don't agree with that.
    %again I apologise I assumed that since callable statements inherit from prepared statements that they would have the pre compiled sql statement functionality of prepared statements,well If you consider in the example I'm about to give maybe you will see my point at least with regards to this.
    The statement that I create uses a connection and is created statically at the start of the program, every time I make a call the same statement and thus connection is used, creating a new connection each time takes up time and resources. and as you know every second counts
    thanks for your thoughts
    Brian.

  • Truncating data in prepared statement

    I'm using a prepared statement to pull data out of one SQL database into a recordSet, and another prepared statement to take the data from the recordSet and insert the data into another SQL database. In the source database, the lastname and firstname fields are both defined as char(25) and the phone field is defined as char(24). In the receiving database, the lastname and firstname fields are each defined as nvarchar(100) and the phone field is defined as nvarchar(50).
    The program will only run successfully if I trim the data in each field to the first 16 characters. Any time it hits a field with more than 16 characters, it throws a SQL Error: String data, right truncation.
    The setObject statements are:
    update.setObject(1,lastname,java.sql.Types.VARCHAR);
    update.setObject(2,firstname,java.sql.Types.VARCHAR);
    update.setObject(3,phone1,java.sql.Types.VARCHAR);
    int rowCount = update.executeUpdate();
    Why can't I push the entire 25-character name fields into the 100-character name fields? And the 24-character phone field into the 50-character phone field?

    mrw127 wrote:
    sun.jdbc.odbc.JdbcOdbcDriver
    I don't know how to tell which version it is.
    It would revert to the ODBC driver version then rather than anything in java.
    I spent a couple hours trying to use com.microsoft.sqlserver.jdbc.SQLServerDriver that I downloaded on Monday but could not get it to work. I even put both .jars in the c:\temp dir, updated my classpath, even rebooted after making the changes, but it could not find the driver. Reverted back to the JdbcOdbcDriver.The current MS driver seems to work adequately and so does the jTDS driver from soucreforge. I would suspect both would support nvarchar correctly.

  • Set char in Prepared Statement

    Hi,
    Can any one let me know how to set Character value in Prepared Statement. I have my table in which the column is of Char type. Now in my prepared statment, I am saying
    PreparedStament pstmt = con.prepareStatement("select ticker from INSTRUMENT_TICKERXREF where ticker = ? ");
    pstmt.setString(1,'F');
    I even tried pstmt.setString(1,"F");
    It gives me incompatible types. Can any please help me on this asap.
    Regards,
    ..Raj

    Hi,
    I just tried using setString(), it does not seem to give any problems. But in any case, you could use setObject() too.
    I tried both setString() and setObject for an example table structure as below:
    create table testchar(col1 CHAR(3));
    insert into testchar('one');
    from java class:
    PreparedStatement pstmt = conn.prepareStatement("select col1 from testchar where col1 = ? ");
    //pstmt.setObject(1,"one");
    pstmt.setString(1,"one");
    Hope that helps.
    Savitha.
    OTN group@IDC

Maybe you are looking for

  • Movie Rental Download

    I recently rented a movie but when I try to download it it says "Error downloading. Tap to retry." I keep tapping and it says the same thing, I even tried downloading in iTunes on the computer and it will not download. How do I fix this or just remov

  • Ejecting a Firewire DV camera daisy chained vis a External Firewire HD

    I have my firewire DV camera daisy chained via my firewire external Hard drive. When I unplug my firewire dv camera, after a little while I get a message on my mac that a device was removed incorrectly and the external firewire dirve dismounts. This

  • FOR/NEXT loop produces Error in ProcessSQL: Subscript out of range

    Hi all, The 2nd FOR/NEXT loop in the following code produces Subscript ouf of Range error: *LOOKUP RATEAPP *DIM MODEL:RATEENTITYDIM= DRIVEDIM.DRIVER_ENTITY *DIM MODEL:RATEACCOUNTDIM= DRIVEDIM.DRIVER *DIM MODEL:INPUTCURRENCYDIM = "EUR" *ENDLOOKUP // S

  • How do I re-find my 'Community Help' preferences?

    I had that 'Access denied' error message whenever I tried to access help within Flash CS5 (that's pretty bad). I searched for far too long and found the obscure solution. During the process I decided it might be safer to access the online help from m

  • The best way to implement business logic to a .JSP ?

    Hi experts, I want to implement some business logic to a .JSP file wich is in my modified <b>com.xxxNew.portal.usermanagement.admin.pa</b>r file! For examle creating different roles for useres by registration dependently what they inseret in the regi