Prepared Statement in MS Access

Hi,
I want to pass a string value for a SELECT statement like this for MS Access:
/** Get the connection */
getConnection();
if (tableName.equals("Confidential_Data")) {
pstmt = conn.prepareStatement("select emp_no, emp_name, project_name from " + tableName + " where emp_name like ?");
try {
pstmt.setString (1, empname);
rs = pstmt.executeQuery();
while (rs.next()) {
Vector row = new Vector();
if (tableName.equals("Security_Data")) {
row.add(Long.toString(rs.getLong(1)));
row.add(rs.getString(2));
row.add(rs.getString(3));
rowData.add(row);
rs.close();
pstmt.close();
closeConnection();
...But no data is fetched.
When I run the query in MS Access by providing the string argument, it gives out result.
Am I missing something?
Any help is appreciated.
Thanks in advance.
Rajeev.

pstmt = conn.prepareStatement("select emp_no,
emp_name, project_name from " + tableName + " where
emp_name like ?");Set the tableName variable up as a PreparedStatement parameter too. So, instead of above, you'd have:
  pstmt = conn.prepareStatement("select emp_no, emp_name, project_name from ? where emp_name like ?");
  pstmt.clearParameters();
  pstmt.setString(1, tablename);
  pstmt.setString(2, emp_name);

Similar Messages

  • Problem with Prepared Statement & MS Access

    Hi
    I have tried to find some info about this but can't see anything specific to what I think the problem may be. Hopefully someone can point me in the right direction.I am trying to get information out of an MS Access database using a Prepared Statement but I am getting strange results.
    When I run the query in the database it gives me the correct totals (�51) for 4 records. When I run the Prepared Statement ,I get 81. Has it got anything to do with the data type I am using( sorry if this is a really basic question). here is my code- the connection etc is elsewhere.
    private void getReportMoneyTotal() throws SQLException
              Calendar todayTotal =Calendar.getInstance() ;
               SimpleDateFormat reportDateFormat = new SimpleDateFormat("dd MM yyyy");
              PreparedStatement preparedT =context.getConnection().prepareStatement(
                   "SELECT Sum(tblSession.Fee) AS Total, Count(tblBooking.BookingID) AS CountOfBookingID FROM tblSession INNER JOIN "+
                   "(tblBooking INNER JOIN tblCustomer_Booking ON tblBooking.BookingID = tblCustomer_Booking.BookingID) ON tblSession.SessionID = tblBooking.SessionID "+
                   "WHERE (((tblBooking.EventDate)>DateAdd('m',-1,#"+reportDateFormat.format(todayTotal.getTime())+"#)) AND ((tblSession.Session)='Morning' Or (tblSession.Session)='Evening')) OR (((tblSession.Session)='Afternoon') AND ((tblBooking.Extension)=Yes))"
              ResultSet resultTotal =preparedT.executeQuery();
              resultTotal.next();
              Double total =resultTotal.getDouble("Total");
              Locale locale = new Locale("GBP");
            NumberFormat gbpFormat = NumberFormat.getCurrencyInstance(locale);
              System.out.println(gbpFormat.format(total));
              preparedT.close();
         }I do realise that my code probably isn't very elegant but I'm only learning!

    Hi Matt--
    I am not clear if you are saving the url with the # # around
    the text or if
    the
    data already contains the # marks.
    When you insert a link, you want to make sure you insert is
    insert into table ( link1) values ( <cfqueryparam
    cfsqltype="cf_sql_varchar"
    value='#linkvaluehere#'> )
    remember to
    1) enclose your data's value inside quotes (some databases
    are picky about
    single v. double quotes).
    2) if it IS in quotes, swap doubles for singles and see if
    that helps.
    3) make sure your data being saved is NOT double hashed like
    '##linkvalueher##'. Double ##'s tell
    Coldfusion not to treat it as a variable.
    hope his helps,
    tami
    "Mattastic" <[email protected]> wrote in
    message
    news:f9c7h0$8ub$[email protected]..
    | Hi Folks,
    |
    | I'm storing a link in a nvarchar field in SQL server,
    www.foo.co.uk, it
    looks
    | and works fine in SQL server. Problem occurs when I setup
    an ADP in Access
    and
    | insert links. Certain links have a hash symbol around them.
    so
    |
    http://www.foo.co.uk, would be #
    http://www.foo.co.uk# which is
    causing
    problems.
    |
    | Can anyone tell me why this is happening? and how to stop
    it?
    |
    | Thankyou
    |

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

  • Prepared Statement, executing  SELECT TOP in Ms Access

    I'm having the following problem. I built an application fetching data without any problem from MS SQL Server, this was using prepared statements. Now i'm having this strange problem with the following query:
    SELECT TOP 1 *
    FROM table
    WHERE appliance_id = ?
    AND ttimestamp_initpk <= ?
    AND ((Type = ?) OR (Type = ?) OR (Type = ?) OR (Type = ?) OR (Type = ?) OR (Type = ?))
    ORDER BY ttimestamp_initpk DESC
    While on SQL Server this fetches just a record, on MS Access it fetches the whole set of records without worrying about TOP instruction.
    That is, it acts like a SELECT * FROM, and this slows down runtime behaviour.
    I'm using sun.jdbc.odbc.JdbcOdbcDriver, is it the problem?
    Thanks, Mirko

    Thanks for your answer, but i'm not sure this is the reason.
    I made one more test: i wrote a .Net application connecting to a MS Access using an ODBC connection. SELECT TOP statement is working fine, so i think i'll try another JDBC driver. Any other solution??
    Thanks,
    Mirko

  • Prepared statement not releasing from access db

    Hello all,
    I have several prepared statements like the following:
    public void storeUpdate(String userId,String ws,String wm,String wl,String wx,String wxx,String bs,String bm,String bl,String bx,String bxx, String tq, String tp,Timestamp ts)
         String updatePurchase = "UPDATE store SET smallWhite=?,medWhite=?,lrgWhite=?,xlrgWhite=?,xxlrgWhite=?,smallBlue=?,medBlue=?,lrgBlue=?,xlrgBlue=?,xxlrgBlue=?,totalQty=?,totalPrice=?,ot=? WHERE playerNo='"+userId+"'";
         try{
             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
             objConn = java.sql.DriverManager.getConnection("jdbc:odbc:myDB","","");
             PreparedStatement ps = objConn.prepareStatement(updatePurchase);
             ps.setString(1, ws);
             ps.setString(2, wm);
             ps.setString(3, wl);
             ps.setString(4, wx);
             ps.setString(5, wxx);
             ps.setString(6, bs);
             ps.setString(7, bm);
             ps.setString(8, bl);
             ps.setString(9, bx);
             ps.setString(10, bxx);
             ps.setString(11, tq);
             ps.setString(12, tp);
             ps.setTimestamp(13,ts);
             ps.executeUpdate();
             ps.close();
             objConn.close();
                catch (SQLException s)
                    System.err.println("DataBase PROBLEM");
                    s.printStackTrace();
                catch (Exception e)
                        System.err.println("Error in updateStore method");
                        e.printStackTrace();
    } The prepared stmts seem to be "hanging on to" the access(dont laugh)table that the prepared stmt just updated. The reason I know this is because when I try to look at the table in access's design view I get a message saying:
    "Microsoft access
    You cant open the table 'store' for modification.
    A query or form bound to the table is open, you may not have permission to open this table in design view, or another user has the table open.
    If you have opened a query or form bound to this table, close it, and then try again to open the table in design view."
    The only way to open the table in design view is to shut down tomcat and restart.
    Should I be worried about this?
    Am i forgetting to close something in my ps?
    TIA!!

    I use PreparedStatement all the time with Access and never have a problem. The only thing I noticed about your code is that if an exception gets thrown in your method, the close statements won't get executed. This might leave the tables locked. You might want to try moving the close statements into a finally block. That way your statement and connection will get closed if an exception gets thrown or not.

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

  • ODBC 'NOW' function in prepared statement?

    I'm writing a class that logs data to a ODBC datasource (using JDK 1.5). I've set up a link to a Microsoft Access database to test against.
    I've written a couple of prepared statements, that all work well. Now, I'm trying to add a timestamp in a column, and things go wrong. I'm not seeing why. Can anyone point out my mistake?
    first, I'm checking if the ODBC datasource has the 'NOW' function available:
    if (!this.con.getMetaData().getTimeDateFunctions().contains(",NOW,") )
      System.err.println("ODBC datasource does not provide the 'NOW' function. Timestamps will not be logged!");
      this.pstmInsertItem =
        con.prepareStatement("INSERT INTO myTable (id, ip, endUser) VALUES (?, ?, ?);
    else
      this.pstmInsertItem =
        con.prepareStatement("INSERT INTO myTable (id, timestamp, ip, endUser) VALUES (?, NOW(), ?, ?);
    }Sadly, once filled out and executed, a SQLException is thrown. getMessage() tells me: "[Microsoft] [ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement."
    A few things that are odd:
    If I remove the 'timestamp,' and 'NOW(),' from the latter prepared statement (thus making it similar to the first query), the query executes fine.
    If I execute the query in MS Access directly, timestamps are logged perfectly (I have to leave out the () after NOW though).
    The statement below does execute perfectly, even though it makes use of another ODBC function: "SELECT MAX(id) FROM myTable WHERE " (...and so on).
    I've tried several variations of the NOW function (NOW, now, NOW() etc) but none of them seem to work. Can someone help me out here?

    Well, one reason to use database-supplied timestamps rather than client-supplied timestamps is that you often have only one database host but may have multiple clients whose system times aren't effectively synchronized. In other words, since a DB date function like SYSDATE can change the source of the time from client to server, it's NOT an exact functional equivalent to the java.sqlTimestamp class. This can be especially true with Swing apps; you don't exactly want an important date to have the client-side date when the user has (accidentally) set the system date ahead 2 months when seeing what day of the week Christmas falls on this year.
    I don't think this reasoning applies to MS access (I'm guessing that the client time is actually used by NOW() in Access - how could it not given the architecture?), but there are lots of other good reasons for being non-portable, not least being when you really truly know you're never ever going to port the code to another DB.
    Portability is just another tool in the toolbox; a good developer uses the right tools for the job and knows when portability is being broken. Newbies of course don't know the value of portability and don't know when they're breaking it.
    And our poor original poster has already pummeled himself about the reserved word...

  • Prepared Statement and DEFAULT identifier

    Does anyone know how to pass the identifier DEFAULT to a PreparedStatement?
    I am processing a text file to import into a database table (Oracle 9i) via JDBC. The user is able to configure what will happen if the data in the file doesn't match the types required by the database and so I do a quick check that the data is of the right type before it gets to the database. The user can choose to have the invalid value replaced with the default associated with that field (as configured on the database table). Eg. Table setup is
    CREATE TABLE "TEST1" (
    "TESTFIELD1" VARCHAR2(40 byte),
    "TESTFIELD2" VARCHAR2(40 byte) NOT NULL,
    "TESTFIELD3" NUMBER(30, 10) DEFAULT 777)
    sample data of 'abc', 'def', 'www' should therefore end up as 'abc', 'def', 777
    The problem I have is that I'm using a PreparedStatement to do the INSERTs (there could potentially be thousands of them).
    The following SQL is what I'm trying to emulate...
    INSERT INTO table (field1, field2, field3) VALUES ('abc', 'def', DEFAULT);
    BUT, I am using a PreparedStatment via JDBC with bind variables ...
    pstmt = con.prepareStatement("INSERT INTO table (field1, field2, field3) VALUES (?, ?, ?)");
    ps.setString(1, "abc");
    ps.setString(2, "def");
    ps.setsomething(3, something); <- what goes here?
    I have no idea what to put in the "something" bits so that DEFAULT is passed through. I obviously can't use setString(3, "DEFAULT"); as I'll just get an Oracle type mismatch error.
    I realise that I could just leave out the 3rd variable and the default would be inserted automatically - but because some of the rows in the input file may have a valid value for field3 I don't always want the default value. Using the straight SQL is not an option due to the performance (or lack thereof).
    Any ideas would be greatly appreciated! Thanks!

    As for the best of my knowledge if you set the value to be null in the prepared Statement while setting that
    for insert statement internally it is set to DEFAULT in ORACLE..
    More over i thought that this will be usefull for u..
    setNull
    public void setNull(int paramIndex,
    int sqlType,
    String typeName)
    throws SQLExceptionSets the designated parameter to SQL NULL. This version of the method setNull should be used for user-defined types and REF type parameters. Examples of user-defined types include: STRUCT, DISTINCT, JAVA_OBJECT, and named array types.
    setNull
    public void setNull(int parameterIndex,
    int sqlType)
    throws SQLExceptionSets the designated parameter to SQL NULL.
    Note: You must specify the parameter's SQL type.
    Parameters:
    parameterIndex - the first parameter is 1, the second is 2, ...
    sqlType - the SQL type code defined in java.sql.Types
    Throws:
    SQLException - if a database access error occurs
    ALL THE BEST

  • Prepared statement takes much longer than statement..

    Hi community,
    At the moment I'm trying to migrate my j2ee application from DB2 to Oracle. I'm using database version 10.2.0.3 and driver version 10.2.0.4.
    After copying all data from DB2 to Oracle, I've started testing the application with the new database. During this process, a problem occurs when using prepared statements.
    For example, when I'm trying to execute the following sql statement:
    SELECT
    LINVIN.BBASE , INVINNUM , INVINNUMALT , LINVIN.LSUPPLIERNUM , LINVIN.COMPANYCODE , ACCOUNT , INVINTXT , INVINSTS , INVINTYP , INVINDAT , RECEIPTDAT , POSTED , POSTINGDATE , CHECKCOSTCENTER , WORKFLOWIDEXT , INVINREFERENCE , RESPONSIBLEPERS , INVINSUM , INVINSUMGROSS , VOUCHERNUM , HASPOSITIONS , LSUPPLIER.AADDRLINE1
    from LINVIN, LSUPPLIER
    where LINVIN.BBASE = LSUPPLIER.BBASE
    and LINVIN.LSUPPLIERNUM = LSUPPLIER.LSUPPLIERNUM
    and LINVIN.BBASE = ? and LINVIN.INVINNUM = ?
    order by LINVIN.BBASE, LINVIN.INVINDAT DESC
    The execution time, when using a simple java.sql.Statement, amounts to 100 millis. But if I execute the same statement with a java.sql.PreparedStatement it takes about 30.000 millis.
    I tried to do a explain plan on both types with the following results:
    With java.sql.Statement:
    PLAN_TABLE_OUTPUT
    Plan hash value: 1286706273
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
    PLAN_TABLE_OUTPUT
    | 0 | SELECT STATEMENT | | 1 | 225 | 4 (0)| 00:00:01 |
    | 1 | NESTED LOOPS | | 1 | 225 | 4 (0)| 00:00:01 |
    | 2 | TABLE ACCESS BY INDEX ROWID| LINVIN | 1 | 136 | 3 (0)| 00:00:01 |
    |* 3 | INDEX UNIQUE SCAN | PK_2540516 | 1 | | 2 (0)| 00:00:01 |
    PLAN_TABLE_OUTPUT
    | 4 | TABLE ACCESS BY INDEX ROWID| LSUPPLIER | 16922 | 1470K| 1 (0)| 00:00:01 |
    |* 5 | INDEX UNIQUE SCAN | PK_177597 | 1 | | 0 (0)| 00:00:01 |
    PLAN_TABLE_OUTPUT
    Predicate Information (identified by operation id):
    3 - access("LINVIN"."BBASE"='PRAK' AND "LINVIN"."INVINNUM"='0010344820')
    5 - access("LSUPPLIER"."BBASE"='PRAK' AND
    "LINVIN"."LSUPPLIERNUM"="LSUPPLIER"."LSUPPLIERNUM")
    With java.sql.PreparedStatement:
    PLAN_TABLE_OUTPUT
    Plan hash value: 957014775
    | Id | Operation | Name | Rows | Bytes |TempSpc| Cost (%CPU)| Time |
    PLAN_TABLE_OUTPUT
    | 0 | SELECT STATEMENT | | 37 | 8325 | | 5850 (1)| 00:01:11 |
    | 1 | MERGE JOIN | | 37 | 8325 | | 5850 (1)| 00:01:11 |
    |* 2 | TABLE ACCESS BY INDEX ROWID| LINVIN | 34 | 4624 | | 3442 (1)| 00:00:42 |
    |* 3 | INDEX FULL SCAN | LINVOICE_LSUPPLIER_FK | 3410 | | | 999 (2)| 00:00:12 |
    PLAN_TABLE_OUTPUT
    |* 4 | SORT JOIN | | 101K| 8824K| 19M| 2408 (1)| 00:00:29 |
    | 5 | INDEX FAST FULL SCAN | LSUPPLIERAL1 | 101K| 8824K| | 329 (1)| 00:00:04 |
    PLAN_TABLE_OUTPUT
    Predicate Information (identified by operation id):
    2 - filter(SYS_OP_C2C("LINVIN"."INVINNUM")=:2)
    3 - filter(SYS_OP_C2C("LINVIN"."BBASE")=:1)
    4 - access("LINVIN"."BBASE"="LSUPPLIER"."BBASE" AND
    "LINVIN"."LSUPPLIERNUM"="LSUPPLIER"."LSUPPLIERNUM")
    filter("LINVIN"."LSUPPLIERNUM"="LSUPPLIER"."LSUPPLIERNUM" AND
    "LINVIN"."BBASE"="LSUPPLIER"."BBASE")
    I checked the tables and the indexes and everything looks fine. I have an index over the where clause (PK), the order by clause and the join criterias. I also analyzed the tables and the indexes and also started a rebuild on them.
    Indexes table LINVIN:
    PK_2540516 --> index on LINVIN(BBASE, INVINNUM)
    LINVOICE_LSUPPLIER_FK --> index on LINVIN(BBASE, LSUPPLIERNUM)
    LINV_INVDAT --> index on LINVIN(BBASE, INVINDAT DESC)
    Indexes table LSUPPLIER:
    PK_177597 --> index on LSUPPLIER(BBASE, LSUPPLIERNUM)
    LSUPPLIERAL1 --> index on LSUPPLIER(BBASE,LSUPPLIERNUM,AADDRESSLINE1) [why is Oracle using this index, when addressline1 isn't in the statement?]
    Can somebody tell me please, why the prepared statement takes a completely different way than the normal statement and how can I get the prepared statement working like the other?
    I would really appreciated, if somebody can help me with this issue, because I'm really getting more and more distressed...
    Thanks in advance,
    Tobias

    With java.sql.Statement:
    Predicate Information (identified by operation id):
    > 3 - access("LINVIN"."BBASE"='PRAK' AND
    "LINVIN"."INVINNUM"='0010344820')> 5 - access("LSUPPLIER"."BBASE"='PRAK' AND
    >
    LINVIN"."LSUPPLIERNUM"="LSUPPLIER"."LSUPPLIERNUM")
    With java.sql.PreparedStatement:
    Predicate Information (identified by operation id):
    > 2 - filter(SYS_OP_C2C("LINVIN"."INVINNUM")=:2)
    3 - filter(SYS_OP_C2C("LINVIN"."BBASE")=:1)> 4 - access("LINVIN"."BBASE"="LSUPPLIER"."BBASE"
    AND
    LINVIN"."LSUPPLIERNUM"="LSUPPLIER"."LSUPPLIERNUM")
    ilter("LINVIN"."LSUPPLIERNUM"="LSUPPLIER"."LSUPPLIERNU
    M" AND
    "LINVIN"."BBASE"="LSUPPLIER"."BBASE")
    the tables and the indexes and everything looks fine.Notice the SYS_OP_C2C function Oracle is applying in your code with the prepared statement, it is doing this because the bind variable is not of the same data type as your column. So it's taking your column in the table, applying a function to convert it into the same data type as your bind variable (which destroys any possibility of using an index).
    If you ensure the prepared statement is binding type for type this should magically go away.

  • Prepared statement problem

    I am trying, for some time now, to implement some sort of bank application that uses DBs to store customers.
    I have been trying to improve my code, the results are interesting since while studing more I saw that the previous code was.....not so good. I am using Prepared statement now as some of you suggested but I cannot surpass this final glich.
         try
                                      try
                                           Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                                            Connection connection=DriverManager.getConnection("jdbc:odbc:customersTable");
                                            Statement stat = connection.createStatement();
                                            ResultSet set = stat.executeQuery("SELECT * FROM CUSTOMERSTABLE");
                                            boolean check = true;
                                            while(set.next())
                                                 String ssnChecked = ssn.getText();
                                                 String SSN = set.getString("ssn");
                                                 if(ssnChecked.equals(SSN))
                                                      JOptionPane.showMessageDialog(null, "SSN already excists");
                                                      check = false;
                                            if(check == true)
                                                  String ssnToDB = ssn.getText();
                                                 String nameToDB = name.getText();
                                                 String surnameToDB = surname.getText();
                                                 String addressToDB = address.getText();
                                                     String phoneToDB = phone.getText();
                                                 String phone2ToDB = phone2.getText();
                                                 String balanceToDB = balance.getText();
                                                 System.out.println(ssnToDB+nameToDB);
                                                 PreparedStatement prstat = connection.prepareStatement("INSERT INTO CUSTOMERSTABLE VALUES ( ????????)");
                                                 prstat.setString(1,ssnToDB);
                                                 prstat.setString(2,nameToDB);
                                                 prstat.setString(3,surnameToDB);
                                                 prstat.setString(4,addressToDB);
                                                 prstat.setString(5,phoneToDB);
                                                 prstat.setString(6,phone2ToDB);
                                                 prstat.setString(7,balanceToDB);
                                                 prstat.executeUpdate();
                                                 prstat.close();
                                                 //String command = "INSERT INTO CUSTOMERSTABLE VALUES ("+ssnToDB+nameToDB+surnameToDB+addressToDB+addressToDB+phoneToDB+phone2ToDB+balanceToDB+")";
                                            connection.close();
                                      catch(ClassNotFoundException exception)
                                           JOptionPane.showMessageDialog(null, "ERROR1");
                                 catch(SQLException exception)
                                      JOptionPane.showMessageDialog(null, "ERROR2");
                                 }This code throws a SQLException that probably has to do with the use of PreparedStatement. Can you help?

    java.sql.SQLException: [Microsoft][&#9576;?&#8319;&#942;?&#940;&#905;&#905;&#940; &#910;&#970;&#9616;&#942;&#973;&#8804;&#973;&#8805; ODBC Microsoft Access]&#9532;&#8804;?&#940;
    &#904;&#905;&#9612;&#906;&#910; &#911;&#943;&#970;&#9600;&#910; COUNT
    ????????????

  • 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

  • Prepare statement to insert a row that contains Blob column. Which way is correct?

    When we make prepare statement to insert a row that contains Blob column. Which way is correct? And what is the difference? Does anyone know?
         1.  Preparestatement.setBlob(parameter number, blob type object)
         2. Preparestatement.setBlob(parameter number, inputstream type object)
    This link show the test I made.
    https://community.oracle.com/thread/3680185?sr=inbox&customTheme=otn

    When we make prepare statement to insert a row that contains Blob column. Which way is correct? And what is the difference? Does anyone know?
         1.  Preparestatement.setBlob(parameter number, blob type object)
         2. Preparestatement.setBlob(parameter number, inputstream type object)
    I answered that in your other thread and provided a link to the JDBC Dev Guide section that discusses how to work with LOBs and BFILEs.
    Did you read that doc section?
    Did you read my reply in your other thread?
    In java a BLOB is just the locator that gives you access to the actual content. In your case you got access by selecting an existing BLOB locator and getting its inputstream. That inputstream is what gives you access to the actual blob content.
    The locator is just that; it specifies the LOCATION of the blob content but it is NOT the content.

  • JDBC: Prepared statements with more parameters than column names

    I'm using the latest version of the JDBC driver - 4.1.5605.100_enu - on Java 1.7, Linux.
    I'm connecting to MS SQL Server 2012 Express Edition using a connection URL of the form jdbc:sqlserver://10.0.0.2;user=username;password=pwd;database=testdb1
    I have a table with two columns. One is an ID (type bigint) and one is numeric(38, 19).
    The following code works exactly as expected:
    PreparedStatement stm = connection.prepareStatement("INSERT INTO myTable(id, num) VALUES (?, ?)")
    // repeatedly set parameters using setLong, setBigDecimal, then addBatch
    stm.executeBatch()
    The following code does not work as expected:
    PreparedStatement stm = connection.prepareStatement("INSERT INTO myTable(id, num) VALUES (?, ?),  (?, ?)");
    stm.setLong(1, 1);
    stm.setBigDecimal(2, new BigDecimal("1.234"));
    stm.setLong(3, 2);
    stm.setBigDecimal(4, new BigDecimal("1.234"));
    stm.addBatch();
    stm.executeBatch();
    The code runs normally in the second case, but the second row inserted contains the wrong value in the "num" column - it's been rounded to 1.0 instead of stored as 1.234.
    I think this may be because the driver does not understand the types of parameters whose indexes are beyond the number of columns in the insert statement. Running the following code on the second prepared statement:
    System.err.println(stm.getParameterMetaData().getParameterTypeName(2)); // prints "numeric"
    System.err.println(stm.getParameterMetaData().getParameterTypeName(4)); // fails with IndexOutOfBoundsException
    As far as I can tell from the JDBC JavaDoc, this usage is valid and ought to work. Certainly it works as expected (including the parameter metadata) using PostgreSQL and their JDBC driver. Is this a bug in Microsoft's driver?

    Hi dtn-cfl,
    Thanks for your waiting.
    Based on my research(using
    SQL Server Profiler to trace DB events), the preparedStatement finally passes the below statements to SQL Server.
    stm.setLong(1, 1);
    stm.setBigDecimal(2, new BigDecimal("1.234"));
    stm.setLong(3, 2);
    stm.setNull(4, Types.DECIMAL);
    declare @p1 int
    set @p1=0
    exec sp_prepexec @p1 output,N'@P0 bigint,@P1 decimal(38,3),@P2 bigint,@P3 decimal(38,0)',N'INSERT INTO myTable(id, num) VALUES (@P0, @P1), (@P2, @P3) ',1,1.234,2,NULL
    select @p1
    Pay attention to the @P3 decimal(38,0),  it seems(I don't have access to JDBC source code so that I have to use seem) that the
    stm.setNull(4, Types.DECIMAL) will finally parsed as a type decimal(38,0). In SQL Server, to a
    decimal datatype,one with smaller scale has a higher precedence. To understand the precedence, please see below code. If you have more interest in data type precedence, you can click
    here.
    declare @num1 decimal(38,3) --scale 3
    declare @num2 decimal(38,2) --scale 2
    set @num1 = 3.225
    set @num2 = 3.22
    select @num1 as num
    union all
    select @num2
    output
    num
    3.23
    3.22
    @num1 get rounded to keep the column data type consistency, namely keep the column as type decimal(38,2)
    Let's go back to your code, if you would like to make your code work properly, please see below.
    stm.setLong(1, 1);
    stm.setBigDecimal(2, new BigDecimal("1.234"));
    stm.setLong(3, 2);
    stm.setNull(4, Types.INTEGER);As per the above data type precedence link, a decimal has a higher precedence than integer, so your decimal will not get rounded.
    Not only the case in your post, but also any data type inconsistency will lead to the rounding problem. See below.
    stm.setLong(1, 1);
    stm.setBigDecimal(2, new BigDecimal("1.234"));
    stm.setLong(3, 2);
    stm.setBigDecimal(4, new BigDecimal("1.2")); // or new BigDecimal("1.23") and any other decimal with different scale leads to rounding problem.
    So when you set parameters for a prepareStatement like "INSERT INTO myTable(id, num) VALUES (?, ?),  (?, ?)" with more than one row, you should pay attention to data type consistency fact.
    The Microsoft JDBC driver for SQL Server may not be that intelligent, however we can't say that is a bug definitely.
    If you have any question, feel free to let me know.
    Eric Zhang
    TechNet Community Support

  • Deployments are in Active state on Cluster but in Prepared state on server

    Hi,
    We initially deployed our application (Oracle Identity Manager 11gR2) on standalone managed server and then convert it into cluster using wlst commands.
    readDomain('/app/oracle/Middleware_OAM/user_projects/domains/oim_domain')
    setDistDestType('JRFWSAsyncJmsModule', 'UDD')
    setDistDestType('OIMJMSModule', 'UDD')
    create('oim_cluster','Cluster')
    assign('Server','oim_server1','Cluster','oim_cluster')
    updateDomain()
    The cluster is created fine and we can start the application successfully and access it. However the problem is that all the deployments are in 'Active' state only under Cluster but in prepared state under the server oim_server1 (though application access working on managed server port). Please advise where we are missing and what could be the wrong?
    Thanks

    Hi,
    1. What if you are trying to access the application page, does it come up ?
    2. Use the below wlst command to get the actual state of the deployed application:
    The deploy command returns a WLSTProgress object that you can access to check the status of the command. The WLSTProgress object is captured in a user-defined variable, in this case, progress.
    wls:/mydomain/serverConfig/Servers> progress= deploy(appName='businessApp',path='c:/myapps/business',createplan='true')
    The previous example stores the WLSTProgress object returned in a user-defined variable, in this case, progress. You can then use the progress variable to print the status of the deploy command. For example:
    wls:/mydomain/serverConfig/Servers> progress.printStatus()
    Current Status of your Deployment:
    Deployment command type: deploy
    Deployment State       : completed
    Deployment Message     : null
    wls:/mydomain/serverConfig/Servers>
    3. Restart all the servers, instances, related DB and check if it helps.
    Thanks,
    Sharmela

  • XML SQL format for Prepared statements in batch mode

    Hi
    I want to use the batch mode in JDBC adapter for inserting huge volume of records with better performance.
    so i need to execute the prepared statements in one batch.   Is the XML SQL format for prepared statements below correct ?to<root>
      <stmt>
        <Customers action="SQL_DML">
          <access> INSERT INTO Customers (CompanyName,Address,CustomerID) VALUES($NAME$,$ADDRESS$,$KEYFIELD$)
          </access>
          <key>
            <NAME>IBM</NAME>
            <ADDRESS>Street 3 </ADDRESS>
            <KEYFIELD>CO</KEYFIELD>
          </key>
          <key>
            <NAME>PWC</NAME>
            <ADDRESS>Street 4 </ADDRESS>
            <KEYFIELD>NO</KEYFIELD>
         </key>
        </Customers>
      </stmt>
    </root>
    Please advise

    Hello Experts
    Please throw some light on the above question.
    Thanks in advance.

Maybe you are looking for