Problem in inserting to MS Access using prepared statement

I am inserting a record in MS Access db and I am using prepared statement. I am encountering an error.... any help I would really appreciate it. So much time figuring out what the problem is....
ConvertText contxt = new ConvertText();
String bday = (String)cbYear.getSelectedItem() +
cbMonth.getItemCount()+(String)cbDay.getSelectedItem();
try{
// load MySQL driver
Class.forName(driver);
// Setup connection to DBMS
Connection conn = DriverManager.getConnection(url);
// Create statement     
Statement stmt     = conn.createStatement();
PreparedStatement insertPersons = conn.prepareStatement(
        "INSERT INTO PERSONS VALUES(" +
     "FIRST_NAME               = ?," +
     "LAST_NAME              = ?," +
     "MIDDLE_NAME               = ?," +
     "NICKNAME              = ?," +
     "GENDER              = ?," +
     "MARITALSTATUS           = ?," +
     "AGE                    = ?," +
     "BIRTHDATE                   = ?," +
     "ADDRESS                  = ?," +
     "RES_PHONE_NUMBER        = ?," +
     "OFFICE_PHONE_NUMBER     = ?," +
     "CELL_NUMBER               = ?," +
     "COMPANY_NAME               = ?," +
     "EMAIL_ADDRESS               = ?," +
     "TIMESTAMP               = ?)"
          insertPersons.setString   (1, tfFirstName.getText());
          insertPersons.setString   (2, tfLastName.getText());
          insertPersons.setString   (3, tfMiddleName.getText());
          insertPersons.setString   (4, tfNickName.getText());
          insertPersons.setString   (5, (String)cbGender.getSelectedItem());
          insertPersons.setString   (6, (String)cbMaritalStatus.getSelectedItem());
          insertPersons.setInt      (7, contxt.formatStringToInt(tfAge.getText()));
          insertPersons.setDate     (8, contxt.formatStringToSQLDate(bday));
          insertPersons.setString   (9, tfAddress.getText());
          insertPersons.setString   (10,tfResPhoneNumber.getText());
          insertPersons.setString   (11,tfOffPhoneNumber.getText());
          insertPersons.setString   (12,tfCellNumber.getText());
          insertPersons.setString   (13,tfCompanyName.getText());
          insertPersons.setString   (14,tfEmailAddress.getText());
          insertPersons.setTimestamp(15, new Timestamp(System.currentTimeMillis()));          
          insertPersons.executeUpdate();
          conn.close();          
JOptionPane.showMessageDialog(null,"Record Inserted!", "INSERT",
                    JOptionPane.INFORMATION_MESSAGE);
}catch (SQLException ex){
System.err.println("==> SQLException: ");
System.out.println("Message:   SQL Exception");
System.out.println("Message:   " + ex.getMessage ());
System.out.println("SQLState:  " + ex.getSQLState ());
System.out.println("ErrorCode: " + ex.getErrorCode ());
JOptionPane.showMessageDialog(null, ex.getMessage() + ex.toString(),"Error", JOptionPane.INFORMATION_MESSAGE);
}catch(Exception ex){
}          ERROR Displayed:
[Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 30. java.sql.SQLException     

Hi cruzdhel,
Your SQL looks incorrect to me.
I am not familiar with that syntax.
I think it should be like this:
PreparedStatement insertPersons =
conn.prepareStatement("INSERT INTO PERSONS (FIRST_NAME," +
                                           "LAST_NAME," +
                                           "MIDDLE_NAME," +
                                           "NICKNAME," +
                                           "GENDER," +
                                           "MARITALSTATUS," +
                                           "AGE," +
                                           "BIRTHDATE," +
                                           "ADDRESS," +
                                           "RES_PHONE_NUMBER," +
                                           "OFFICE_PHONE_NUMBER," +
                                           "CELL_NUMBER," +
                                           "COMPANY_NAME," +
                                           "EMAIL_ADDRESS," +
                                           "TIMESTAMP)" +
"values (?," +
        "?," +
        "?," +
        "?," +
        "?," +
        "?," +
        "?," +
        "?," +
        "?," +
        "?," +
        "?," +
        "?," +
        "?," +
        "?," +
        "?)");Hope this helps.
Good Luck,
Avi.

Similar Messages

  • How to Insert Character using Prepared statement

    Hi All,
    Can anyone let me know how can I insert character using prepared statement.
    Thanks
    Sameer

    In the future JDBC related questions should be posted into the JDBC forum.
    Can you please provide some more information about what you are trying to do? It isn't clear to me. Are you trying to update a CHAR field?

  • Advantages of using prepared statement..... ?

    can anyone please tell me that what r the advantages of using prepared statements.
    for eg in case if statement object is executed inside a for loop where query is executed multiple times the sql query is compiled outside loop and therefore compilation is done only once. which makes sense
    But if there the query is not executed multiple times then what is the real benifit of using prepared statement . because the statement object will be closed after executing the query.
    and a new statement object will be created when other user access the same code.
    please clearify my doubts
    thanks
    Pankaj

    Other advantages of using PreparedStatement:
    1. It's easier to create SQL that looks like "Select This, That, TheOther from Something where ID=? and Usage=?" than to try to generate that with string concatenations.
    2. You don't have to deal with escaping quote characters that happen to appear in strings you want to insert in your database.
    3. PreparedStatements can do some things that Statement can't, such as updating very large text columns.

  • Query slow when executing using prepared statement compared to sqlDeveloper

    Oracle version is 10.2.0.1.0.
    I have got a query which when submitted from java code using prepared statement and parameter substitutions, takes more than 20 seconds to give results.
    I can see this SELECT sql sitting there when I run Monitor Sessions through sqlDeveloper, with its wait time increasing and then finally getting through. During that time no other SQLs are waiting.
    DURING THAT TIME then I am able to run the same query (with values included) multiple times using sqlDeveloper, and it gives results in no time.
    Sqldeveloper connects using thin client using lib provided by oracle in windows.
    Java code runs from linux and uses the thin client using lib provided by oracle in linux.
    Both are hitting the same DB running on a separate Linux machine.
    What could be the cause of this problem?
    What db parameters, queries should I run to identify the bottleneck?
    Edited by: user10390517 on Jun 14, 2010 3:06 AM

    Hi Rob,
    at least you should see some differences in the statistics for the different child cursor (the one for the execution in the application should show at least a higher value for ELAPSED_TIME). I would use something like the following query to check the information for the child cursors:
    select sql_id
         , PLAN_HASH_VALUE
         , CHILD_NUMBER
         , EXECUTIONS
         , ELAPSED_TIME
         , USER_IO_WAIT_TIME
         , CONCURRENCY_WAIT_TIME
         , DISK_READS
         , BUFFER_GETS
         , ROWS_PROCESSED
      from v$sql
    where sql_id = your_sql_idRegards
    Martin

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

  • Using prepared statements in java

    Hi
    I have question on proper usage of prepared statements.
    PreparedStatement ps;
    public methoda(){
    ps=conn.prepareStatement(sqlQry);
    ps.setInt(1,2);
    ps.execute();
    In the above case I am creating new references to prepared statement (ps)each time I invoke methoda. So am I still using the advantage of prepared statements that is prepare a statement once and execute it multiple times. Or in the above case, the DB knows that this has been executed before and does not prepare it second time and just executes it.
    thanks

    The database stores execution plans for previous statements that were executed. So even tho you create a new PreparedStatement each time, it will still be an improvement.
    Even if you don't use prepared statements those plans are cached. Problem is that you must reuse the exact same sql to get the benefit.
    So if you do
    select password from users where user="dave";
    a hundred times, the database most likely will only create the plan once.
    Problem is of course, that
    select password from users where user="yelapa";
    is a completely different sql statement sofar as the database knows.
    Thus, the value of Prepared statements.
    select password from users where user=?
    is what the database sees no matter what user is running it.

  • How to use prepared statement - For Everyone Help

    public String count()
    int count = 0;
    String fetchsize = "";
    try
    Connection conn = getOADBTransaction().getJdbcConnection();
    Statement statement = conn.createStatement();
    String Query = "select count(*) count from fnd_lookups where lookup_type like 'SAPE_BILL_TO_SHIP_TO_UPDATE'";
    ResultSet resultset = statement.executeQuery(Query);
    while (resultset.next())
    count = (int)resultset.getInt("count");
    fetchsize = ""+count;
    catch(Exception e)
    return fetchsize;
    }

    Hi,
    we can use prepare statement in Co....
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    try
    PreparedStatement prpdStmt1 = am.getOADBTransaction().getJdbcConnection().prepareStatement("select full_name from per_all_people_f where person_id='"+empid+"' ");
    ResultSet rs=prpdStmt1.executeQuery(); //Cursor fetch row
    while(rs.next())
    empname=rs.getString(1);
    catch(Exception e)
    System.out.println("Exception is"+e.getMessage());
    t1.setValue(pageContext,empname);
    Thanks
    nani

  • Problem storing date in MS Access using JSP

    Hi all,
    Can anyone please help me storing date in MS Access using Java i am getting errors. I think it is probably because MS Access take "date/month". I am entering a string with date and month example
    1st October as "0110". I don't know how to enter a date in MS Access.
    Here is my code.
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <%@page import="java.io.*"%>
    <%@page import="java.sql.*"%>
    <HTML>
    <HEAD>
    <TITLE>  </TITLE>
    </HEAD>
    <BODY>
    <%
       String emplno = request.getParameter("emplno");
       String date = request.getParameter("date");
       String proposal = request.getParameter("proposals");
       String network1 = request.getParameter("network");
       String suppassociates = request.getParameter("suppasso");
       String intmngt = request.getParameter("intmgt");
       String client[] = request.getParameterValues("client");
       String client1= request.getParameter("client1");
       String clientunit[] = request.getParameterValues("clientunit");
       String clientunit1=request.getParameter("clientunit1");
       int staffid = Integer.parseInt(emplno);
       double proposalunit=Double.parseDouble(proposal);
       double suppliersunit=Double.parseDouble(suppassociates);
       double networkunit=Double.parseDouble(network1);
       double internalmgtunit=Double.parseDouble(intmngt);
       Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
       Connection con = DriverManager.getConnection("jdbc:odbc:finalmp" );
       String activities= "INSERT INTO StaffActivities (StaffID,Date,ProposalUnit,NetworkingUnit,SuppliersAssociatesUnit,InternalMGTUnit) VALUES (?,?,?,?,?,?)";
       PreparedStatement pstmt = con.prepareStatement(activities);
       pstmt.setInt(1,staffid);
       pstmt.setString(2,date);
       pstmt.setDouble(3,proposalunit);
       pstmt.setDouble(4,suppliersunit);
       pstmt.setDouble(5,networkunit);
       pstmt.setDouble(6,internammgtunit);
       pstmt.executeUpdate();
       //String emplno="hello";
       //String entered_date="hello";
       //int access_date=0;
       //int user_date=0;
       if(pstmt!=null)
         pstmt.close();
       if(con!=null)
         con.close();
    %>  
    </BODY>
    </HTML>

    i hope this can help you
    public static String convertToISOFormat(Date dateTime) {
            // ISO Format: 'YYYY-MM-DD HH:MM:SS'
            String returnValue = fillLeft(String.valueOf(dateTime.getYear()+1900), 4,
                    '0')
                    + "-"
                    + fillLeft(String.valueOf(dateTime.getMonth()+1), 2, '0')
                    + "-"
                    + fillLeft(String.valueOf(dateTime.getDate()), 2, '0')
                    + " "
                    + fillLeft(String.valueOf(dateTime.getHours()), 2, '0')
                    + ":"
                    + fillLeft(String.valueOf(dateTime.getMinutes()), 2, '0')
                    + ":" + fillLeft(String.valueOf(dateTime.getSeconds()), 2, '0');
            return returnValue;
        }

  • ? in SQL Queries and not using prepared statements

    Using EclipseLink 1.1.1
    Prepared Statements are disabled
    In our production server something went wrong and one of our Read Queries started erroring. A DatabaseException was thrown and we log the "getQuery.getSQLString()" statement. We found this query in the logs:
    SELECT t1.ID, t1.NAME, t1.DESCRIPTION, t1.EXTREFID, t1.STYLESHEET, t1.DDSVNVERSION, t1.FIRSTNAME, t1.LASTNAME, t1.EMAILADDR, t1.PHONENUMBER, t1.ADDRESS, t1.ADDRESS2, t1.CITY, t1.STATE, t1.POSTALCODE, t1.COUNTRY, t1.ADMINACCTNAME, t1.HASDOCUMENTS, t1.HASTIMEDNOTIFICATIONS, t1.STATUS, t1.ENTRYDATE, t1.EVALEXPDATE, t1.LASTREMINDDATE, t1.FULLUSERS, t1.LIMUSERS, t1.REQUSERS, t1.ISENTERPRISE, t1.EXPDATE, t1.ISDISABLED, t1.DISABLEDDATE, t1.NEEDLICENSEAGREEMENT, t1.ISWARNINGDISABLED, t1.LOCALE, t1.TIMEZONE, t1.CURRENCY, t1.DOMAIN, t1.DOCUMENTSIZE, t1.EXTRADOCUMENTSTORAGE, t1.ONDEMANDOPTIONS, t1.SSOTYPE, t1.RESELLERID, t1.ACCOUNTREPID, t1.LASTUSAGEREPORTDATE, t1.NEXTUSAGEREPORTDATE, t1.USAGEREPORTATTEMPTS FROM T_SSOOPTIONS t0, T_CUSTOMERS t1 WHERE *((((t0.SSOENABLED = ?) AND (t1.SSOTYPE IN (?, ?))) AND (UPPER(t1.DOMAIN) = ?)) AND (t0.CUSTOMERID = t1.ID))*
    Notice the values weren't entered into the where clause. We had to bounce the application to fix the problem. I've never seen this before. I've added more debugging statements to the code - so if this happens again in the future I'll have more information to report on. In the mean time I'm wondering if anyone else has every seen a problem of this nature.

    Database error due to invalid SQL statement.
    I don't have a stack, we were catching the exception and not printing the stack :(
    Like I mentioned in my first post, I added more debugging code (e.printStackTrace()). I understand this is hard to track down without more information. I was just hoping you guys had seen something like this before and had any insight. Like I mentioned before: this is on our production server. I've never seen this type of error before. That particular server (we run in a cluster mode) had been up for several days and then started generating that error. IT bounced the node and everything went back to normal. We have been using toplink for about 5 years now and have never seen this problem, until August 3rd 2009. The only thing that has changed recently is our migration from toplink 10 to EclipseLink. I was wondering if anyone knows if anything had changed in EclipseLink/toplink 11 with the generation of SQL queries.
    I'll keep looking. There is more debugging code in there now. Since the error was "Database error due to invalid SQL statement" this implies the SQL was generated, exited that part of the code and was sent to the db where it failed. I'm afraid the printStackTrace won't help if this error happens again.

  • Using Prepared Statement to pass array of primary key

    How can i use the PreparedStatement to send the array (It can be variable depend upon the user selection) of primary keys to database
    For example I want prepare statement somthing like this
    public Collection findByIds(long[] ids){
    String sql = "select * from Person where person_id IN (?)"
    PreparedStatement ps = conn.prepareStatement(sql)
    ps.setArray();
    Any example this regard will be appreciated. Database is Oracle

    Hi!
    I found your question about sending an Array to a SQL phrase.
    (http://forum.java.sun.com/thread.jsp?forum=48&thread=150061)
    I have found the same problem.
    If you have resolved that problem more elegant than build a SQL phrase dinamic please send me an email with your solution at [email protected] .
    Example :
    I try to send a parameter to a phrase like this
    select * from tableName where fieldName in ?
    where ? is like [ "a", "b", "c"] - this collection may have different number of elements.
    I don't want to create a SQL phrase dinamic (it's ugly) like this
    select from tableName where fieldName = "a" or fieldName = "b" or fieldName = "c"

  • How to use prepared statement by Application Module on ADF?

    Hello
    i am using a prepared statement on the view side of my project,
    this is my code, i'm not sure about using this code.
    AppModuleGFTImpl am = (AppModuleGFTImpl) Configuration.createRootApplicationModule(amDef,config);
    try {
    ps =am.getDBTransaction().createPreparedStatement("Select * from XXXXXX where kullanici_id=? and sifre=?",0);
    ps.setString(1, kullanici);
    ps.setString(2, sifre);
    rs = ps.executeQuery();
    if (rs.next()) {
    girebilir = true;
    } else {
    girebilir = false;
    ps.close();
    rs.close();
    //am.getDBTransaction().closeTransaction(); ? I'm not Sure
    //Configuration.releaseRootApplicationModule(am, true); ? I'm not Sure
    Is it True? How we use this code on the project view side? Must we close Transaction, or release application Module.
    thanks for interest.
    sorry my english.

    Hello, for the SP you can use something like this in your application module
      private static final String BULKSTAMMENN =
        "begin IVA_OWNER.IVA_UI_ALGEMEEN_PCK.USM_SNELLE_INVOER_GUI( P_RLE_ID => :1, P_AANTAL => :2, P_OJR_JAAR => :3, P_RAS_ID => :4, P_TOELICHTING => :5, P_SUCCES => :6 ); end;";
    public void bulkStamen ( int rasId, int telerId, int jaar, int aantal, String toelichting ) {
        CallableStatement bulkStamenSP = null;
        try {
          bulkStamenSP = getDBTransaction().createCallableStatement( BULKSTAMMENN, 0 );
          bulkStamenSP.setInt( 1, telerId );
          bulkStamenSP.setInt( 2, aantal );
          bulkStamenSP.setInt( 3, jaar );
          bulkStamenSP.setInt( 4, rasId );
          bulkStamenSP.setString( 5, toelichting );
          bulkStamenSP.registerOutParameter( 6, Types.VARCHAR );
          bulkStamenSP.executeUpdate();
        } catch ( Exception e ) {
          log.warning( "Aanroep naar " + BULKSTAMMENN + " gefaald, " + e.getMessage() );
        } finally {
          if ( bulkStamenSP != null ) {
            try {
              bulkStamenSP.close();
            } catch ( Exception e ) {
              log.warning( e.getMessage() );
        log.info( "Stammen bulk uitgevoerd voor " + rasId + " " + telerId + " " + jaar + " " + aantal + " " +
                  toelichting );
      }You can then drag this method onto your page or right into your task flow if your using JDev 11.
    Also you can access it from a backing bean although the methods above are preferred
    -Anton

  • Can not use prepared statement

    i am using a prepared statement for the following query but the query does not give me an output where as if i use a create statement i am getting my result
    can any one say why is it ? or what the problem is
                String strQuery = " select lic.lic_id  licId, "+                                                   " lic.license_nbr licNo, "+                                                   " lt.display_desc licType "+                                                   " from colamgr.cola_entities ent, "+                                                 " colamgr.cola_licenses lic, "+                                                 " colamgr.cola_lic_types lt, "+                                                 " colamgr.cola_boards    boa "+                                           " where (( 'E'= ? and ent.ent_id = ?) "+                                           " or ( 'L'= ? and lic.lic_id = ?)) "+                                           " and lic.ent_id = ent.ent_id "+                                           " and lic.license_status ='ACTIVE' "+                                           " and lic.lt_id = lt.lt_id "+                                           " and boa.boa_id = lt.boa_id "+                                           " and (( 'E' = ? and (lt.print_ent_addr_ind <> 'N' "+                                           " or (lt.print_lic_addr_ind <> 'N' and lic.addr1 is null))) "+                                           " or  ( 'L' = ? and lt.print_lic_addr_ind <> 'N')) "+                                           " UNION "+                                           " select  empl_lic.lic_id  licId, "+                                                   " empl_lic.license_nbr licNo, "+                                                   " empl_lt.display_desc licType "+                                                                                     " from colamgr.cola_entities  ent, "+                                                 " colamgr.cola_licenses  lic, "+                                                 " colamgr.cola_lic_types lt, "+                                                 " colamgr.cola_lic_xrefs lx, "+                                                 " colamgr.cola_licenses  empl_lic, "+                                                 " colamgr.cola_lic_types empl_lt, "+                                                 " colamgr.cola_boards    empl_boa "+                                           " where (( 'E'= ? and ent.ent_id = ?) "+                                           " or ( and lic.lic_id = ? and 'L'= ? )) "+                                           " and lic.ent_id              = ent.ent_id "+                                           " and lic.lic_id              = lx.lic_id "+                                           " and lic.license_status      ='ACTIVE' "+                                           " and lx.approval_ind        = 'A' "+                                           " and lx.begin_date          is not null "+                                           " and lx.end_date            is null "+                                           " and lx.lic_id_child        = empl_lic.lic_id "+                                           " and empl_lt.lt_id          = empl_lic.lt_id "+                                           " and empl_boa.boa_id        = empl_lt.boa_id "+                                           " and empl_lic.license_status = 'ACTIVE' "+                                           " and lic.lt_id              = lt.lt_id "+                                           " and exists (select 1 "+                                                       " from colamgr.cola_lic_types lt1 "+                                                       " where lt1.lt_id = empl_lic.lt_id "+                                                       " and ((lt1.xref1_ind in ('M') "+                                                       " and  lt1.xref1_lt_id = lt.lt_id "+                                                       " and  (('E'= ? and (lt1.print_xref1_ent_addr_ind <> 'N' "+                                                       " or (lt1.print_xref1_lic_addr_ind <> 'N' and lic.addr1 is null))) "+                                                       " or    ( 'L' = ? and lt1.print_xref1_lic_addr_ind <> 'N'))) "+                                                       " or  (lt1.xref2_ind in ('M') "+                                                       " and  lt1.xref2_lt_id = lt.lt_id "+                                                       " and  (('E'= ? and (lt1.print_xref2_ent_addr_ind <> 'N' "+                                                       " or (lt1.print_xref2_lic_addr_ind <> 'N' and lic.addr1 is null))) "+                                                       " or    ( 'L' = ? and lt1.print_xref2_lic_addr_ind <> 'N'))) "+                                                       " or  (lt1.xref1_ind in ('O') "+                                                       " and  (lt1.xref1_lt_id = lt.lt_id or lt1.xref2_lt_id = lt.lt_id) "+                                                       " and  (('E'= ? and (lt1.print_xref1_ent_addr_ind <> 'N' "+                                                       " or (lt1.print_xref1_lic_addr_ind <> 'N' and lic.addr1 is null))) "+                                                       " or    ('L' = ? and lt1.print_xref1_lic_addr_ind <> 'N'))))) "+                                                       " order by 6 desc, 7 asc ";

    here is my code which works . when i replace the ? ( where i am checking strAddrtype ='L' using set string it doesn't work . i wanted to know why its not working any help is much appreciated.
    thanks .
            public ArrayList getReprintLicenses(String strEntId, String strLicId, String strAddrType)
              ArrayList alMasterLicList = new ArrayList();
               String strQuery = " select lic.lic_id   licId, "+
                                                     " lic.license_nbr licNo, "+
                                                     " lt.display_desc licType, "+
                                                     " colamgr.COLA_CHK_RENEW_STAT(lic.lic_id) renewStatus, "+
                                                     " 0, "+
                                                     " SUBSTR(lic.License_nbr,1,4), "+
                                                     " SUBSTR(lic.License_nbr,5) "+
                                              " from cola_entities ent, "+
                                                   " cola_licenses lic, "+
                                                   " cola_lic_types lt, "+
                                                   " cola_boards    boa "+
                                              " where ((?= 'E' and ent.ent_id = ? ) "+
                                              " or ("+strAddrType+" = 'L' and lic.lic_id = ?)) "+
                                              " and lic.ent_id = ent.ent_id "+
                                              " and lic.license_status ='ACTIVE' "+
                                              " and lic.lt_id = lt.lt_id "+
                                              " and boa.boa_id = lt.boa_id "+
                                              " and ((?= 'E' and (lt.print_ent_addr_ind <> 'N' "+
                                              " or (lt.print_lic_addr_ind <> 'N' and lic.addr1 is null))) "+
                                              " or   ("+strAddrType+" = 'L' and lt.print_lic_addr_ind <> 'N')) "+
                                              " UNION "+
                                              " select  empl_lic.lic_id  licId, "+
                                                      " empl_lic.license_nbr licNo, "+
                                                      " empl_lt.display_desc licType, "+
                                                      " COLA_CHK_RENEW_STAT(empl_lic.lic_id) renewStatus, "+
                                                      " 1, "+
                                                      " SUBSTR(lic.License_nbr,1,4), "+
                                                      " SUBSTR(lic.License_nbr,5) "+
                                              " from cola_entities  ent, "+
                                                   " cola_licenses  lic, "+
                                                   " cola_lic_types lt, "+
                                                   " cola_lic_xrefs lx, "+
                                                   " cola_licenses  empl_lic, "+
                                                   " cola_lic_types empl_lt, "+
                                                   " cola_boards    empl_boa "+
                                              " where ((? = 'E' and ent.ent_id =?) "+
                                              " or ("+strAddrType+" = 'L' and lic.lic_id =?)) "+
                                              " and lic.ent_id              = ent.ent_id "+
                                              " and lic.lic_id              = lx.lic_id "+
                                              " and lic.license_status      ='ACTIVE' "+
                                              " and lx.approval_ind         = 'A' "+
                                              " and lx.begin_date           is not null "+
                                              " and lx.end_date             is null "+
                                              " and lx.lic_id_child         = empl_lic.lic_id "+
                                              " and empl_lt.lt_id           = empl_lic.lt_id "+
                                              " and empl_boa.boa_id         = empl_lt.boa_id "+
                                              " and empl_lic.license_status = 'ACTIVE' "+
                                              " and lic.lt_id               = lt.lt_id "+
                                              " and exists (select 1 "+
                                                          " from cola_lic_types lt1 "+
                                                          " where lt1.lt_id = empl_lic.lt_id "+
                                                          " and ((lt1.xref1_ind in ('M') "+
                                                          " and  lt1.xref1_lt_id = lt.lt_id "+
                                                          " and  ((? = 'E' and (lt1.print_xref1_ent_addr_ind <> 'N' "+
                                                          " or (lt1.print_xref1_lic_addr_ind <> 'N' and lic.addr1 is null))) "+
                                                          " or    (?= 'L' and lt1.print_xref1_lic_addr_ind <> 'N'))) "+
                                                          " or   (lt1.xref2_ind in ('M') "+
                                                          " and  lt1.xref2_lt_id = lt.lt_id "+
                                                          " and  ((?= 'E' and (lt1.print_xref2_ent_addr_ind <> 'N' "+
                                                          " or (lt1.print_xref2_lic_addr_ind <> 'N' and lic.addr1 is null))) "+
                                                          " or    (? = 'L' and lt1.print_xref2_lic_addr_ind <> 'N'))) "+
                                                          " or   (lt1.xref1_ind in ('O') "+
                                                          " and   (lt1.xref1_lt_id = lt.lt_id or lt1.xref2_lt_id = lt.lt_id) "+
                                                          " and  ((? = 'E' and (lt1.print_xref1_ent_addr_ind <> 'N' "+
                                                          " or (lt1.print_xref1_lic_addr_ind <> 'N' and lic.addr1 is null))) "+
                                                          " or    (? = 'L' and lt1.print_xref1_lic_addr_ind <> 'N'))))) "+
                                                          " order by 6 desc, 7 asc ";
              try
                con = getDSconn();
         //  stmt = con.createStatement();
              pstmt=con.prepareStatement(strQuery);
               // rs = stmt.executeQuery(strQuery);
            pstmt.setString(1,strAddrtype);
             pstmt.setString(2,strEntId);
             pstmt.setString(3,strLicId);
             pstmt.setString(4,strAddrtype);
             pstmt.setString(5,strAddrtype);
             pstmt.setString(6,strEntId);
             pstmt.setString(7,strLicId);
             pstmt.setString(8,strAddrtype);
             pstmt.setString(9,strAddrtype);
             pstmt.setString(10,strAddrtype);
             pstmt.setString(11,strAddrtype);
    pstmt.setString(12,strAddrtype);
    pstmt.setString(13,strAddrtype);
              rs=pstmt.executeQuery();
                while (rs.next())
                  LicenseeForm licenseInfo = new LicenseeForm();
                  licenseInfo.setLicId(rs.getString(1));
                  licenseInfo.setLicNo(rs.getString(2));
                  licenseInfo.setLicType(rs.getString(3));
                  //licenseInfo.setBoard(rs.getString(4));
                  licenseInfo.setRenewStatus(rs.getString(4));
                  alMasterLicList.add(licenseInfo);
                rs.close();
                pstmt.close();
                con.close();
                con = null;
              catch (RuntimeException re)
                    throw re;
              catch(Exception e)
              { e.printStackTrace();
                try
                  rs.close();
                  pstmt.close();
                  con.close();
                  con = null;
                catch(Exception i){}
              finally
                try
                  pstmt.close();
                  con.close();
                  con = null;
                catch(Exception i){}
              return alMasterLicList;     
           

  • When to use prepared statement in java?

    Hi all,
    If we have query like select * from {tablename} (Here tablename is the variable) then will the use of prepared staement improve the performance? My guess is use of statement in this case is a better option rather than prepared statement as the tablename may change for every other query.I think are not useful if tablename changes.They are useful only when the where clause has dynamic values.

    cantor wrote:
    Are you sure that your approach is possible? The next example causes exception for me.
    PreparedStatement ps = conn.prepareStatement("select * from ?");
    ps.setString(1, "TABLE_NAME");
    ps.executeQuery();
    I didn't say that he should solve it in that way. He should create one prepared statement like this "select a, b, c from tablename1" and another prepared statement when he wants to execute "select d, e, f from tablename2"
    >
    And as I understand, this code will not improve perfomance (and even will not work). As I said it can.
    Prepared statements make possible usage compiled queries inside DB. When DB gets prepared statement call, it need to parse it only once. And it can collect some statistic to improve execution plan. But when table name is not specified, this approach will not work.Yes it might. There are database drivers that can cache prepared statements and it's isn't likely that he executes that query on more than e.g. 20 tables?
    The database can also cache compiled statements in a cache.
    Kaj

  • Does a Database Control use Prepared Statements?

    When I add a method to a database control I have to supply the SQL for that method. Under the covers does the database control convert that SQL into a prepared statement? Is this documented anywhere?
    Thanks for the help!
    Rob

    Rob,
    it seems not be documented, but the Database Control always uses a PreparedStatement internally.
    -Kai

  • Using prepared statements

    hi guys, kinda need help in understanding the prepared statement. the code below is my example on how to get a date based on a serial number. how do i get the right expiry date? i do not know whether the code is right or wrong.
    String reqSerial = request.getParameter("serial_no");
    PreparedStatement psGetExpiry =
                             con.prepareStatement("SELECT expiry_date from identity WHERE serial_no=?");          
    ResultSet rsGetExpiry = null;          
    psGetExpiry.setString(1, reqSerial);  //shouldn't here be setDate instead of setString
                                                                      //cause what i want is the expiry date
    rsGetExpiry = psGetExpiry.executeQuery();thx in advance
    lost,
    hayati

    String reqSerial = request.getParameter("serial_no");
    PreparedStatement psGetExpiry =
                             con.prepareStatement("SELECT expiry_date from identity WHERE serial_no=?");          
    ResultSet rsGetExpiry = null;          
    psGetExpiry.setString(1, reqSerial);
    rsGetExpiry = psGetExpiry.executeQuery();
    while (rsGetExpiry.next())
         expiryDate = rsGetExpiry.getDate(1);    <----- get your expiry date here

Maybe you are looking for