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

Similar Messages

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

  • Unable to set string in prepared statement

    Hi all,
    I just want to set an string to a prepared stmt.
    the setting string is in the format..... the integers with comma saparated....
    str="23,55,22"
    ps.setString(1,str)
    The prepare statement is taking only the first integer... i.e. 23
    can any one help me out..........
    thanks in advance,
    prakhyath

    if i am not mistaken.... If I create the Prepared
    Statement after receiving the arguments that are to
    be provided to it.... the actual purpose.. Of using
    a prepared statement is not served at all....Not creating a new Statement each time, is only one of the purposes of PreparedStatement. In this case, since the arguments should be ints (and I hope you are checking that), then it doesn't make much of a difference. But a PreparedStatement is alos used to easily facilitate the proper quoting and escaping of the parameters set, which almost eliminates any chance of an SQL injection attack. There are also a few other convienences associated with a PreparedStatement, but, in this case, you are probabyl right in that there is no advantage of PreparedStatement over Statement (as long as you are checking that the arguments provided are actually ints, otherwise you are opening yourself up to an injection attack).

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

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

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

  • How to set the number of rings for the agent phone rings before it get the not prepared state

    hi, how to set the number of rings for the agent phone rings?  before it get the not prepared state.
    thanks

    The following assumes that you are using ICM with an IPIVR etc (not using CVP), as the answer is different for CVP
    What you are looking for is called "Ring no answer time".  It is set in the Agent Desk Setting List tool.
    Regards,
    Kevin

  • Oracle Cached Prepared Statement

    We recently upgraded from WL 8.1 SP3 to WL 9.2 and in the process updated the JDBC Driver for Oracle from 10.2.0.1 to 10.2.0.2. After we went live we started seeing issue in one table. The table contains some special character which is not suppose to be there.
    Here is the code & table details
    PreparedStatement pstmt = cn.prepareStatement("INSERT INTO INFO_TABLE(user_name,user_status) values (?,?)");
    pstmt.setString(1,requestObject.getUserName());
    if(requestObject.isValidUser)
    pstmt.setInt(2,requestObject.getStatus());
    }else
    pstmt.setNull(2,Types.VARCHAR);
    cn.commit();
    Table description:
    USER_NAME VARCHAR2(60);
    USER_STATUS VARCHAR2(5);
    - The USER_STATUS columns valid values are 0-4 or NULL.
    The problem is on certain occasions the valid user value in the table is some special character. I got the ascii value of this character as 128. We don't know yet whether setting int value and varchar (null) value on two different flow (but cached prepared statement) is the issue.
    We can fix the code to use uniform data type but we need to be sure this is what causing the problem. Further when I read the docs http://e-docs.bea.com/wls/docs90/jdbc_admin/jdbc_datasources.html
    I can associate the problem I face with this pointer however as I said, we need some sort of confirmation to make this change in the production code.
    Here is what I am specifically looking for
    1. Is there a way to confirm this problem?
    2. Can we log the prepared statement being executed and the binded value being sent to the Oracle DB?
    I suspect the VARCHAR null type is being casted to int value 128.
    Would really appreciate any pointers on this.
    Thanks

    Purushothaman Thambu wrote:
    We recently upgraded from WL 8.1 SP3 to WL 9.2 and in the process updated the JDBC Driver for Oracle from 10.2.0.1 to 10.2.0.2. After we went live we started seeing issue in one table. The table contains some special character which is not suppose to be there.
    Here is the code & table details
    PreparedStatement pstmt = cn.prepareStatement("INSERT INTO INFO_TABLE(user_name,user_status) values (?,?)");
    pstmt.setString(1,requestObject.getUserName());
    if(requestObject.isValidUser)
    pstmt.setInt(2,requestObject.getStatus());
    }else
    pstmt.setNull(2,Types.VARCHAR);
    cn.commit();
    Table description:
    USER_NAME VARCHAR2(60);
    USER_STATUS VARCHAR2(5);
    - The USER_STATUS columns valid values are 0-4 or NULL.
    The problem is on certain occasions the valid user value in the table is some special character. I got the ascii value of this character as 128. We don't know yet whether setting int value and varchar (null) value on two different flow (but cached prepared statement) is the issue.
    We can fix the code to use uniform data type but we need to be sure this is what causing the problem. Further when I read the docs http://e-docs.bea.com/wls/docs90/jdbc_admin/jdbc_datasources.html
    I can associate the problem I face with this pointer however as I said, we need some sort of confirmation to make this change in the production code.
    Here is what I am specifically looking for
    1. Is there a way to confirm this problem?
    2. Can we log the prepared statement being executed and the binded value being sent to the Oracle DB?
    I suspect the VARCHAR null type is being casted to int value 128.
    Would really appreciate any pointers on this.
    ThanksHi. I don't think there's any issue with WebLogic here, but the code you show
    might confuse some drivers. I highly recommend using setString for all
    varchar/char/varchar2 columns, not setInt(). If requestObject.getStatus()
    has to return an int, try this:
    if(requestObject.isValidUser)
    pstmt.setString(2, (""+ requestObject.getStatus()) );
    Joe

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

  • Connection/ResultSets/Prepared Statement opening and closing

    Hi all another question that was sparked by a thread that I recently read. I believe it was duffmo who got the code from jverd. The code I am referring to is to have an open and close connection specified in a Utility or Database class. I wanted to know if there was any issues with having methods that open and close connections/result sets/ preparedStatements. Currently I am putting the finally blocks inside each of my methods. There is obvious benefits to putting the methods in a class on their own (namely code re-use) but I wanted to know if there are any dangers. (This may seem like a dumb question, but I've found from experience it's the things that you don't know that will cost you loads of time).
    thanks again.

    Hi all another question that was sparked by athread
    that I recently read. I believe it was duffmo who
    got the code from jverd. Generally speaking it's fine.
    But as always you may have some long term design
    issues to think about. If you build a simple
    framework that consists of one class and that does
    all that your program does then great.
    Once you start add more complexity though you'll want
    to be careful that you aren't reinventing the Spring
    wheel or even ending up implementing your own
    connection pool. Both of which, judging from posts
    here seem to happen from time to time.
    So I guess all in all, yes it's much better than
    scattering the code all about but depending on what
    you are going to be doing with it you may want to
    look at the various ORM frameworks to see if they are
    really the direction you should be going in.Thanks for the information cotton. I just wanted to make certain that it was a sensible thing to do. When I had first asked about connections I was told they should be opened an closed in the same spot, unfortunately I took that explanation a little too much to heart, and started opening and closing every connection resultset and prepared statement in each of the DAO classes that I was using.
    Guess it's going to be a bit of work to refactor, but worth it for the cleaner code that will result.

  • Could not find prepared statement with handle %.

    Greetings. I've seen several posts for this error on the web, but no clear cut answers. I captured the code below in profiler, with the intention of replaying in mgmt studio.
    However, the attempt end in the following error: "Could not find prepared statement with handle 612."
    declare @p1 int
    set @p1=612
    declare @p2 int
    set @p2=0
    declare @p7 int
    set @p7=0
    exec sp_cursorprepexec @p1 output,@p2 output,N'@P0 int,@P1 int,@P2 int,@P3 int,@P4 bit',N'EXEC dbo.mySproc @P0,@P1,@P2,@P3,@P4 ',4112,8193,@p7 output,219717,95,NULL,1,0
    select @p1, @p2, @p7
    Something noteworthy is that my sproc only has 5 input parameters, but this makes it look like it has many more.
    How do I manipulate the code enough to make it work in mgmt studio? Thanks!
    TIA, ChrisRDBA

    In profiler you would normally see RPC:Starting and RPC:Completed. The statement shown in RPC staring is what you need to pick because as Erland explained, completed would show "funky" behavior.
    Balmukund Lakhani | Please mark solved if I've answered your question, vote for it as helpful to help other users find a solution quicker
    This posting is provided "AS IS" with no warranties, and confers no rights.
    My Blog |
    Team Blog | @Twitter
    Author: SQL Server 2012 AlwaysOn -
    Paperback, Kindle

  • Problem in prepared Statement

    hi,
    i have used following prepared Statement for the update in database.
    Can any one tell me that,How can i use date in following method.
    I have 4 field for date as given below:(BOLD shown)
    I have used String in that place.
    It is not working.
    PreparedStatement pstatement = conn.prepareStatement(
    "UPDATE sec_mast SET catg_code=?, vou_no=?, vou_date=?, vou_amt=?, due_date1=?, due_date2=?, mat_date=? where sec_no=? ");
    pstatement.setInt(1,Integer.parseInt(request.getParameter("catg_code")));
    pstatement.setString(2,request.getParameter("vou_no"));
    pstatement.setString(3,request.getParameter("vou_date"));
    pstatement.setInt(4,Integer.parseInt(request.getParameter("vou_amt")));
    pstatement.setString(5,request.getParameter("due_date1"));
    pstatement.setString(6,request.getParameter("due_date2"));
    pstatement.setString(7,request.getParameter("mat_date"));
    pstatement.setInt(8,Integer.parseInt(request.getParameter("sec_no")));
    int rowCount = pstatement.executeUpdate();
    conn.setAutoCommit(false);
    conn.setAutoCommit(true);
    plz help me

    thanx for u r reply.
    MY whole code is shown as below:
    This page is for the updating the values in database..
    <html>
    <body>
    <table>
    <tr>
    <td>
    <%@ page import="javax.servlet.*" %>
    <%@ page import="javax.servlet.http.*" %>
    <%@ page language="java" import="java.sql.*" %>
    <%
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection conn=DriverManager.getConnection("jdbc:odbc:pf","scott","ttlscott");
    System.out.println("got connection");
    %>
    <%
    String action = request.getParameter("action");
    // Check if an update is requested
    if (action != null && action.equals("update")) {
    conn.setAutoCommit(false);
    PreparedStatement pstatement = conn.prepareStatement(
    "UPDATE sec_mast SET sec_no=? , catg_code=?, face_val=?, pur_val=?, int_paid=?, int_recd=?, brkr=?, vou_no=?, vou_date=?, vou_amt=?, due_date1=?, due_date2=?, lf_no=?, mat_date=? where tot_val=? ");
    pstatement.setInt(1,Integer.parseInt(request.getParameter("sec_no")));
    pstatement.setInt(2,Integer.parseInt(request.getParameter("catg_code")));
    pstatement.setInt(3,Integer.parseInt(request.getParameter("face_val")));
    pstatement.setInt(4,Integer.parseInt(request.getParameter("pur_val")));
    pstatement.setInt(5,Integer.parseInt(request.getParameter("int_paid")));
    pstatement.setInt(6,Integer.parseInt(request.getParameter("int_recd")));
    pstatement.setInt(7,Integer.parseInt(request.getParameter("brkr")));
    pstatement.setString(8,request.getParameter("vou_no"));
    pstatement.setString(9,request.getParameter("vou_date"));
    pstatement.setInt(10,Integer.parseInt(request.getParameter("vou_amt")));
    pstatement.setString(11,request.getParameter("due_date1"));
    pstatement.setString(12,request.getParameter("due_date2"));
    pstatement.setString(13,request.getParameter("lf_no"));
    pstatement.setString(14,request.getParameter("mat_date"));
    pstatement.setInt(15,Integer.parseInt(request.getParameter("tot_val")));
    int rowCount = pstatement.executeUpdate();
    conn.setAutoCommit(false);
    conn.setAutoCommit(true);
    %>
    <%
    // Create the statement
    Statement statement = conn.createStatement();
    ResultSet rs = statement.executeQuery
    ("SELECT * from sec_mast ");
    %>
    <%
    // Iterate over the ResultSet
    while ( rs.next() ) {
    %>
    <tr>
    <form action="security_update.jsp" method="get">
    <input type="hidden" value="update" name="action">
    <td><input value="<%= rs.getInt("sec_no") %>" name="sec_no"></td>
    <td><input value="<%= rs.getInt("catg_code") %>" name="catg_code"></td>
    <td><input value="<%= rs.getInt("face_val") %>" name="face_val"></td>
    <td><input value="<%= rs.getInt("pur_val") %>" name="pur_val"></td>
    <td><input value="<%= rs.getInt("int_paid") %>" name="int_paid"></td>
    <td><input value="<%= rs.getInt("int_recd") %>" name="int_recd"></td>
    <td><input value="<%= rs.getInt("brkr") %>" name="brkr"></td>
    <td><input value="<%= rs.getInt("tot_val") %>" name="tot_val"></td>
    <td><input value="<%= rs.getString("vou_no") %>" name="vou_no"></td>
    <td><input value="<%= rs.getDate("vou_date") %>" name="vou_date"></td>
    <td><input value="<%= rs.getInt("vou_amt") %>" name="vou_amt"></td>
    <td><input value="<%= rs.getDate("due_date1") %>" name="due_date1"></td>
    <td><input value="<%= rs.getDate("due_date2") %>" name="due_date2"></td>
    <td><input value="<%= rs.getString("lf_no") %>" name="lf_no"></td>
    <td><input value="<%= rs.getDate("mat_date") %>" name="mat_date"></td>
    <td><input type="submit" value="Update"></td>
    </form>
    </tr>
    <%
    %>
    </table>
    <%
    // Close the ResultSet
    rs.close();
    // Close the Statement
    statement.close();
    // Close the Connection
    conn.close();
    } catch (SQLException sqle) {
    out.println(sqle.getMessage());
    } catch (Exception e) {
    out.println(e.getMessage());
    %>
    </td>
    </tr>
    </body>
    </html>

  • Oracle Prepared Statement and spaces in field

    I have a field that is defined as char(10). It has characters like '39' in it. When I select against it using standard SQL (where clause) I get results. When I use it in the where clause of a prepared statement it does not return any rows.
    If I have the field defined as char(2) the prepared statement works.
    If I have the field defined as varchar2(10) and loaded with '39' the prepared statement works.
    If I have the field defined as varchar2(10) and loaded with '39 ' the prepared statement returns no results.
    I really do not think this is a JDBC problem. However, since Oracle's site basically <expletive deleted>, I am hoping someone here has a solution.
    Thanks in advance if you can help.

    Let me clarify.
    I cannot remove the whitespace from the data in the database. I do not need the whitespace to do the query if I am not using a Prepared Statement. This seems to be a problem with the way Oracle is handling the prepared statement. (hence.. my thinking that this is really not a JDBC problem at all.. but I could be wrong.)

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

Maybe you are looking for

  • The iTunes Library cannot be saved. An unknown error occured (-1450)

    Well I've been researching this for about 2 hours now on the apple forums and on other outside sources. For those who are unaware of the problem basically itunes gives an error saying that the library could not be saved and when itunes is started up

  • How to recover deleted files from iPod

    All the contents of my iTunes music folder were deleted. When I connected my iPod it was autosynced with the empty iTunes music folder and everything on the iPod got deleted too. (No warning, no undo.) Does anyone know of a utility proven to recover

  • WLSE Radio Scan Problems

    I have recently set up WDS at a remote campus. I scheduled a radio scan for 4:00am so as not to interfere with active users. The scan completed but not successfully. I got an error message regarding the WDS and I can not determine the reason. I have

  • Need help timing titles on black video

    Here is what I've been doing but maybe there is another (better way) to do it- I select Black Video from Edit and it automatically shows up at the beginning of the timeline. Next I select Title from Edit and type the title, intros, etc. The title wil

  • Unable to start SDM service

    I downloaded NWsneak preview(Java stack) and installed. I think I did the installation as per the instructions given. From SAP Management Console -> when I right click on J2E -> start Its not starting the servive J2EE server. J2EE Server, the status