Prepared Statement with SQL 'IN' Clause

Hi,
I am trying to write a JDBC SQL call to a database using a prepared statement, the call looks something like:
select *
from table
where field in (?, ? ,?)
this thing is that i don't know how many 'IN' parameters are needed until runtime (they come from a List), so is there an easy way of dealing with this, I haven't been able to find any information on this problem anywhere?

>
Hmmm...more expensive than say doing a query on on 2 billion rows with no index?
More expensive than doing a cross server join?
More expensive than doing a restore?
I knew that someone would point this out. :)
I just tried to exaggerate the importance of cursor sharing. This is one of the most important topic in DBMS world, but quite often ignored by JAVA world. I hope that you understand my good intention.
>
2. Insert data corresponding to bind variable to "T". Interesting idea. Please provide the algorithm for that. The only ones I can come up with
1. Involved creating a "dynamic" SQL for the insert
2. Doing multiple cross network inserts.
The first of course is exactly what you said your solution prevented. The second will be more expensive than sending a single dynamically created select.Hopefully, this is not just an "interesting" idea, but very common technique in DBMS. Actually one of the common techniques. There are couple of ways to handle this kind(variable number of bind variables in "IN" clause) of problem.
What i commented was that the simplest one. It's like this:
(based on Oracle)
SQL> create global temporary table bind_temp(value int);
PreparedStatement stmt = con.prepareStatement("INSERT INTO bid_temp VALUES(?)");
for(...) {
     stmt.setInt(1, aValue)
     stmt.addBatch();
stmt.executeBatch();
Statement stmt2 = con.executeQuery("SELECT * FROM target_table WHERE id IN (bind_temp)");
...Doesn't it look pretty? Pretty for both Java developers and DBAs.
By virtue of the mechanism of batch processing, the total DBMS call is just twice and you need just 2 completely sharable SQL statements.
(Hopefully you might understand that Oracle global temporary table is just session scope and we don't need them to be stored permanently)
Above pattern is quite beneficial than these pattern of queries.
SELECT * FROM target_table WHERE id IN (?)
SELECT * FROM target_table WHERE id IN (?,?)
SELECT * FROM target_table WHERE id IN (?,?,?)
SELECT * FROM target_table WHERE id IN (?,?,?,?,.......,?)
If you have large quantity of above patterns of queries, you should note that there are another bunch of better techniques. I noted just one of them.
Hope this clairfies my point.

Similar Messages

  • Prepared Statement with ORDER BY

    I am trying to use order by with prepared statement but it is not ordering.
    String sql = "SELECT * FROM MATERIAL WHERE (LOWER(NAMEE) LIKE ('%' || ? || '%') ORDER BY ? ";
    PreparedStatement ps=CM.getStatement(sql);
    ps.setString(1,p);
    ps.setString(2,sort);
              ResultSet r = ps.executeQuery();
    Can any one tell me how do I use prepared statement with order by

    You can not parameterize column names and such, only literals. You should build the ORDER BY clause dynamically.

  • 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

  • Could not find prepared statement with handle 13

    Hi,
    I'm having a terrible problem: When I try to execute a SQL Query the following exception is thrown:
    * "java.sql.SQLException: [Macromedia][SQLServer JDBC Driver][SQLServer]Could not find prepared statement with handle 13."
    This exception is thrown is this line:
    boolean returnResultSet = ((PreparedStatement)sqlStatement).execute();
    The sqlStatement object is a java.sql.PreparedStatement that was received as a Statement in the method definition.
    The following query is being executed in this PreparedStatement:
    SELECT id_promocao, ds_nome, id_tipo, ds_sinopse, dt_lancamento, pt_site, pt_caminho_relativo, fl_ativo FROM TAB_CINE_GM ORDER BY ds_nome
    I'm using Macromedia JRun 4 build 61650 and I'm using MS-SQL Server 2000 as a database server.
    If anyone can help, I'll thanks a lot.
    Helcio Chaves
    S�o Paulo - SP - Brazil
    [email protected]

    There is a common way to check runtime type:
    if (sqlStatement instanceof PreparedStatement)
    returnResultSet = ((PreparedStatement)sqlStatement).execute();
    else
    returnResultSet = sqlStatement.execute();
    }By the way - I can't understand why you're trying to cast sqlStatement to PreparedStatement? It doesn't matter at all due to so-called polymorphism of all Java methods (except static ones). Anyway execute() will run for PreparedStatement but bot for Statement
    Enjoy,
    Pavel

  • FindByPrimaryKey: Could not find prepared statement with handle 3

    I've inherited a WL61 application and been asked to make it work under WL81. We're using SQL Server 2000. We only access two tables. The XML got auto-converted during the upgrade, but I had to correct the RDBMS column names in the weblogic-cmp-jar.xml
    The application mostly works except the findByPrimaryKey fails with:
    ERROR ExecuteThread: '14' for queue: 'weblogic.kernel.Default' Administrator : TargetSessionBean - Error finding promotion with ID <2>
    javax.ejb.FinderException: Problem in findByPrimaryKey while preparing or executing statement: 'weblogic.jdbc.wrapper.PreparedStatement_weblogic_jdbc_base_BasePreparedStatement@95':
    java.sql.SQLException: [BEA][SQLServer JDBC Driver][SQLServer]Could not find prepared statement with handle 3.
    java.sql.SQLException: [BEA][SQLServer JDBC Driver][SQLServer]Could not find prepared statement with handle 3.
    at weblogic.jdbc.base.BaseExceptions.createException(Unknown Source)
    at weblogic.jdbc.base.BaseExceptions.getException(Unknown Source)
    I've checked the database table and the row exisits with the appropriate PK (in this case a promotion with ID <2>).
    In the WL61 version the findByPrimaryKey was explicitly defined in the weblogic-cmp-rdbms-jar.xml as follows:
    <finder>
    <method-name>findByPrimaryKey</method-name>
    <method-params>
    <method-param>com.fujitsu.ftxs.corema.server.PromotionPK</method-param>
    </method-params>
    <finder-query><![CDATA[ (= $0 promotionId) ]]></finder-query>
    <finder-expression>
    <expression-number>0</expression-number>
    <expression-text><![CDATA[@0.promotionId]]></expression-text>
    <expression-type>int</expression-type>
    </finder-expression>
    </finder
    But I understand that with WL81 I should no longer define this - it's done implicitly - so I've removed this finder definition.
    Any help appreciated. Thanks,
    - Andy Abel

    I fixed it by switching from the using the BEA driver:-
    DriverName="weblogic.jdbc.sqlserver.SQLServerDriver"
    URL="jdbc:bea:sqlserver://host:1433"
    And using the Microsoft Driver instead:-
    DriverName="com.microsoft.jdbc.sqlserver.SQLServerDriver"
    url=jdbc:microsoft:sqlserver://host:1433
    If anyone can explain why the Microsoft Driver works and the BEA driver does not I'd like to know.
    Thanks,
    - Andy Abel

  • Could not find prepared statement with handle 1.

    [Macromedia][SQLServer JDBC Driver][SQLServer]Could not find prepared statement with handle 1.
    I'm getting this error message in what appear to be random ways. The first time I look at a page I might not get it, but the second time I might. I discovered that removing a cfqueryparam tag worked, but that is not really a safe solution. I checked that the cf_sql_type matched the database field, and in one case changed a cf_sql_varchar to a cf_sql_char so it would match a SQL Server nchar(10) field. But still these errors. Any ideas? I've not had any luck Googling this.
    I should add that I'm running Coldfusion 9 as a Tomcat webapp on a Linux server. The database is SQL Server 2005, I think.

    Here's the one that is breaking now:
    <cfquery name="CheckCredentials" datasource="#application.crossreg_dsn#">
                                            SELECT [name_first]+' '+[name_last] as name
                                                        ,p.[uni]
                                                        ,p.email
                                                        ,p.role_id
                                                         ,r.role_name
                                                      ,p.external_program_id
                                              FROM [CrossReg].[dbo].[People] p
                                               INNER JOIN dbo.Roles r on r.role_id = p.role_id
                                              WHERE uni = <cfqueryparam cfsqltype="cf_sql_char" value="#Session.username#">
    </cfquery>
    Session.username is being returned from a CAS authentication system. I've never had troubles with it before.

  • Prepared Statement with "INTERVAL ? DAY" clause

    Hi,
    I am having problems when using a INTERVAL ? DAY clause in a
    preparedStatement in Oracle 8i with the classes12.zip jdbc
    driver.
    The code following code:
    String sql1 =
    "select from my_table where created_ts > SYSDATE -
    INTERVAL '10' DAY";
    String sql2 =
    "select from my_table where created_ts > SYSDATE -
    INTERVAL '?' DAY";
    String sql3 =
    "select from my_table where created_ts > SYSDATE -
    INTERVAL ? DAY";
    try {
    st = con.prepareStatement(sql1);
    ResultSet rs = st.executeQuery();
    System.out.println("1 successful");
    catch (Exception e) {
    System.err.println(e);
    try {
    st = con.prepareStatement(sql2);
    st.setInt(1, 10);
    ResultSet rs = st.executeQuery();
    System.out.println("2 successful");
    catch (Exception e) {
    System.err.println(e);
    try {
    st = con.prepareStatement(sql3);
    st.setInt(1, 10);
    ResultSet rs = st.executeQuery();
    System.out.println("3 successful");
    catch (Exception e) {
    System.err.println(e);
    produces this output:
    1 successful
    java.sql.SQLException: ORA-01036: illegal variable name/number
    java.sql.SQLException: ORA-00933: SQL command not properly ended
    Can anybody help me figuring out what's wrong with the 2nd or
    3rd prepared statement?
    Thanks
    Bernie

    Hi,
    I am having problems when using a INTERVAL ? DAY clause in a
    preparedStatement in Oracle 8i with the classes12.zip jdbc
    driver.
    The code following code:
    String sql1 =
    "select from my_table where created_ts > SYSDATE -
    INTERVAL '10' DAY";
    String sql2 =
    "select from my_table where created_ts > SYSDATE -
    INTERVAL '?' DAY";
    String sql3 =
    "select from my_table where created_ts > SYSDATE -
    INTERVAL ? DAY";
    try {
    st = con.prepareStatement(sql1);
    ResultSet rs = st.executeQuery();
    System.out.println("1 successful");
    catch (Exception e) {
    System.err.println(e);
    try {
    st = con.prepareStatement(sql2);
    st.setInt(1, 10);
    ResultSet rs = st.executeQuery();
    System.out.println("2 successful");
    catch (Exception e) {
    System.err.println(e);
    try {
    st = con.prepareStatement(sql3);
    st.setInt(1, 10);
    ResultSet rs = st.executeQuery();
    System.out.println("3 successful");
    catch (Exception e) {
    System.err.println(e);
    produces this output:
    1 successful
    java.sql.SQLException: ORA-01036: illegal variable name/number
    java.sql.SQLException: ORA-00933: SQL command not properly ended
    Can anybody help me figuring out what's wrong with the 2nd or
    3rd prepared statement?
    Thanks
    Bernie

  • Executiong prepared statement with Like% in SQL Query?

    Hi,
    We are developing GUI project.In which we need to retrieve the contract details based on the Name which we enter in eVision page.Here we will not enter the whole name,we will enter only the part of the name,for example if the actual name is Sun Seebeyond,I will enter only Su.So if there are five records in data base which starts the name with Su.Then it should return the five names..
    For this I am using the prepared statement as
    select name,contractid from table1 where name Like '?%'.
    Here my runtime input value will set to this parameter ?.When I execute this qry in my project I am getting error as "Unable to set parameters on the Object: Invalid parameter index 1".
    If I replace the ? with Su in query itself ,then it works fine..
    Please let me know is there any effective way,using which I can solve..
    Thanks,
    Renga.S.

    Hi,
    This option I already tried and it work fine too.
    I am looking for an option ,where we can handle with in the Query,so we dont need to write any code appending % into the actual valus.
    Thanks,
    Renga.S.

  • Help with SQL MODEL Clause

    I have the privilege of performing a very tedious task.
    We have some home grown regular expressions in our company. I now need to expand these regular expressions.
    Samples:
    a = 0-3
    b = Null, 0, 1
    Expression: Meaning
    1:5: 1,2,3,4,5
    1a: 10, 11, 12, 13
    1b: 1, 10, 11
    1[2,3]ab: 120, 1200, 1201, ....
    It get's even more inetersting because there is a possibility of 1[2,3]a.ab
    I have created two base queries to aid me in my quest. I am using the SQL MODEL clause to solve this problem. I pretty confident that I should be able to convert evrything into a range and the use one of the MODEL clause listed below.
    My only confusion is how do I INCREMENT dynamically. The INCREMENT seems to be a constant in both a FOR and ITERATE statement. I need to figure a way to increment with .01, .1, etc.
    Any help will be greatly appreciated.
    CODE:
    Reference:          http://www.sqlsnippets.com/en/topic-11663.html
    Objective:          Expand a range with ITERATE
    WITH t AS
    (SELECT '2:4' pt
    FROM DUAL
    UNION ALL
    SELECT '6:9' pt
    FROM DUAL)
    SELECT pt AS code_expression
    -- , KEY
    -- , min_key
    -- , max_key
    , m_1 AS code
    FROM t
    MODEL
    PARTITION BY (pt)
    DIMENSION BY ( 0 AS KEY )
    MEASURES (
                        0 AS m_1,
                        TO_NUMBER(SUBSTR(pt, 1, INSTR(pt, ':') - 1)) AS min_key,
                        TO_NUMBER(SUBSTR(pt, INSTR(pt, ':') + 1)) AS max_key               
    RULES
    -- UPSERT
    ITERATE (100000) UNTIL ( ITERATION_NUMBER = max_key[0] - min_key[0] )
    m_1[ITERATION_NUMBER] = min_key[0] + ITERATION_NUMBER
    ORDER BY pt, m_1
    Explanation:
    Line numbers are based on the assupmtion that "WITH t AS" starts at line 5.
    If you need detailed information regarding the MODEL clause please refer to
    the Refrence site stated above or read some documentation.
    Partition-
    Line 18:     PARTITION BY (pt)
                   This will make sure that each "KEY" will start at 0 for each value of pt.
    Dimension-
    Line 19:     DIMENSION BY ( 0 AS KEY )     
                   This is necessary for the refrences max_key[0], and min_key[0] to work.
    Measures-
    Line 21:      0 AS m_1
                   A space holder for new values.
    Line 22:     TO_NUMBER(SUBSTR(pt, 1, INSTR(pt, ':') - 1)) AS min_key
                   The result is '1' for '1:5'.
    Line 23:     TO_NUMBER(SUBSTR(pt, INSTR(pt, ':') + 1)) AS max_key                                        
                   The result is '5' for '1:5'.
    Rules-
    Line 26:     UPSERT
                   This makes it possible for new rows to be created.
    Line 27:     ITERATE (100000) UNTIL ( ITERATION_NUMBER = max_key[0] - min_key[0] )
                   This reads ITERATE 100000 times or UNTIL the ITERATION_NUMBER = max_key[0] - min_key[0]
                   which would be 4 for '1:5', but since the ITERATION_NUMBER starts at 0, whatever follows
                   is repaeted 5 times.
    Line 29:     m_1[ITERATION_NUMBER] = min_key[0] + ITERATION_NUMBER
                   m_1[ITERATION_NUMBER] means m_1[Value of Dimension KEY].
                   Thus for each row of KEY the m_1 is min_key[0] + ITERATION_NUMBER.
    Reference:          http://www.sqlsnippets.com/en/topic-11663.html
    Objective:          Expand a range using FOR
    WITH t AS
    (SELECT '2:4' pt
    FROM DUAL
    UNION ALL
    SELECT '6:9' pt
    FROM DUAL)
    , base AS
    SELECT pt AS code_expression
    , KEY AS code
    , min_key
    , max_key
         , my_increment
    , m_1
    FROM t
    MODEL
    PARTITION BY (pt)
    DIMENSION BY ( CAST(0 AS NUMBER) AS KEY )
    MEASURES (
                        CAST(NULL AS CHAR) AS m_1,
                        TO_NUMBER(SUBSTR(pt, 1, INSTR(pt, ':') - 1)) AS min_key,
                        TO_NUMBER(SUBSTR(pt, INSTR(pt, ':') + 1)) AS max_key,     
                        .1 AS my_increment     
    RULES
    -- UPSERT
              m_1[FOR KEY FROM min_key[0] TO max_key[0] INCREMENT 1] = 'Y'
    ORDER BY pt, KEY, m_1
    SELECT code_expression, code
    FROM base
    WHERE m_1 = 'Y'
    Explanation:
    Line numbers are based on the assupmtion that "WITH t AS" starts at line 5.
    If you need detailed information regarding the MODEL clause please refer to
    the Refrence site stated above or read some documentation.
    Partition-
    Line 21:     PARTITION BY (pt)
                   This will make sure that each "KEY" will start at 0 for each value of pt.
    Dimension-
    Line 22:     DIMENSION BY ( 0 AS KEY )     
                   This is necessary for the refrences max_key[0], and min_key[0] to work.
    Measures-
    Line 24:      CAST(NULL AS CHAR) AS m_1
                   A space holder for results.
    Line 25:     TO_NUMBER(SUBSTR(pt, 1, INSTR(pt, ':') - 1)) AS min_key
                   The result is '1' for '1:5'.
    Line 26:     TO_NUMBER(SUBSTR(pt, INSTR(pt, ':') + 1)) AS max_key                                        
                   The result is '5' for '1:5'.
    Line 27:     .1 AS my_increment     
                   The INCREMENT I would like to use.
    Rules-
    Line 30:     UPSERT
                   This makes it possible for new rows to be created.
                   However seems like it is not necessary.
    Line 32:     m_1[FOR KEY FROM min_key[0] TO max_key[0] INCREMENT 1] = 'Y'
                   Where the KE value is between min_key[0] and max_key[0] set the value of m_1 to 'Y'
    */

    Of course, you can accomplish the same thing without MODEL using an Integer Series Generator like this.
    create table t ( min_val number, max_val number, increment_size number );
    insert into t values ( 2, 3, 0.1 );
    insert into t values ( 1.02, 1.08, 0.02 );
    commit;
    create table integer_table as
      select rownum - 1 as n from all_objects where rownum <= 100 ;
    select
      min_val ,
      increment_size ,
      min_val + (increment_size * n) as val
    from t, integer_table
    where
      n between 0 and ((max_val - min_val)/increment_size)
    order by 3
       MIN_VAL INCREMENT_SIZE        VAL
          1.02            .02       1.02
          1.02            .02       1.04
          1.02            .02       1.06
          1.02            .02       1.08
             2             .1          2
             2             .1        2.1
             2             .1        2.2
             2             .1        2.3
             2             .1        2.4
             2             .1        2.5
             2             .1        2.6
             2             .1        2.7
             2             .1        2.8
             2             .1        2.9
             2             .1          3
    15 rows selected.--
    Joe Fuda
    http://www.sqlsnippets.com/

  • XSQL Using bind params with sql LIKE clause

    I am unable to use a bind-param with the LIKE clause in a SELECT statement.
    eg call .../temp.xsql?name=N
    XSQL query is this:
    <xsql:query max-rows="-1" bind-params="name">
    SELECT last_name
    FROM emp
    WHERE last_name LIKE '?%'
    </xsql:query>
    I have tried a few combinations so far with no success eg:
    WHERE last_name LIKE '{@name}%'
    WHERE last_name LIKE ?||%
    Any ideas?

    I highly recommend using XSQL's real bind variable feature wherever you can. You can read about it in the XSQL Online Documentation (Search for the "Using Bind Variables" section).
    Using this feature is more performant and more secure than using textual substitution variables.
    Here's what your page looks like using textual substitution:
    <page connection="UTD4" xmlns:xsql="urn:oracle-xsql">
      <xsql:query null-indicator="yes" >
        SELECT * FROM TC_HL7_SEG WHERE SEGMENT_CODE LIKE '{@code}%'
      </xsql:query>
    </page> .
    And here's what it would look like using real bind variables:
    <page connection="UTD4" xmlns:xsql="urn:oracle-xsql">
      <xsql:query null-indicator="yes" bind-params="code">
        SELECT * FROM TC_HL7_SEG WHERE SEGMENT_CODE LIKE ?||'%'
      </xsql:query>
    </page> .
    Using real bind variables allows the database to avoid reparsing the SQL statement everytime, which improves performance.
    Steve Muench
    JDeveloper/BC4J Development Team
    Author, Building Oracle XML Applications

  • 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

  • Using once created prepared statement with different connections in Oracle

    Can I use same statement cash using different connections in Oracle
    For example I have a prepared statement p1. After its using i close connection (return it to the pool)
    Next time I want use p1 statement using another connection.
    Question : When I creat p1 in second time ,is it returned from cash or created as a new statement. And what I should do to use once prepared statement using differend connections.
    Thaks.

    As far as I know a PreparedStatement lives and dies with the Connection that created it. So, you cannot use a PreparedStatement with other Connection instances than the one that created it.
    You will have to recreate the PreparedStatement for each time you open a connection, or use the same PreparedStatement and NOT close the Connection in between. The last suggestion can be risky though, if you never close the connection...
    Jakob Jenkov
    www.jenkov.com

  • Prepared Statement with IN Operator

    Hello all, do anyone know how to use IN operator in a prepared statement? For ex.,
    "select name from user where user_no in (?)"
    If I do preparedStatement.setString(1, "2, 3, 4") and execute it, it would give me an ORA-01722: invalid number exception. Any help or pointer will be appreciated. Thanks.
    yien

    You can't (easily) pass a comma-separated list to a SQL statement. If you want to pass N values straight to a PreparedStatement, you would need N bind variables, i.e.
    select name from user where user_no in (?, ?, ?)I would tend to either pass an array to a stored procedure that returned a REF CURSOR for the SELECT or create a pipelined table function that parsed the comma-separated list into a table structure.
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • Best Practice: Combine prepared statements with ;

    Hi,
    I would like to know what the best prctice is for combining prepared statements to give the query below
    INSERT INTO my_table (value) VALUES (?); SELECT LAST_INSERT_ID()The reason for this is that i have written a simple DB wrapper to handle my database connections and queries based on a property file containing sql strings. I would prefer not to change this wrapper code, but be able to specify combined queries in the sql string if possible.
    Thanks in advance

    Have you thought about using Batch statements ?

  • Performance issue doing a prepare statement with LIKE

    Hi
    I'm doing a preparestatement like this
    select foo
    from bar
    where des like ?
    and then do the prepare with the string 'foo%'
    If I do the prepare of this variable, the query is very slow. If I don't do the prepare, the query is very fast. Can anyone help me out on this? DBA's will kill me if I don't use prepare statements but users will kill be if the query is slow...
    Thank you!
    HappyGuy

    As indicated in the last reply this probably has to do with use of string literals over bound variables
    With a prepared statement the optimiser dosen't get the chance to use histograms against your data... so whilst it might be more efficent to drive off an index for some of the searches it looses access to the data (histograms) that enable it to make this decission...
    Hints are probably the way to go... if your sure that driving off a index is always going to be the most efficent...
    Using explain (inside of JDeveloper9i or turning on the autotrace functionality inside of sqlplus) will give you some idea of how Oracle would drive the query if you use a string literal
    Dom

Maybe you are looking for

  • Delete from wwv_flow_file_objects$ where file name like 'p1_name'

    I am having an issue deleting an object in my apex application. I have uploaded an object into the application i can open the application but i cannot delete from that application. I can delete it when i login to the server and provide this command:

  • CD in Flash not working anymore

    Hi, A couple of years back I've produced a CD-Rom. It is basically a main Flash movie loaded in an HTML page which, through specific buttons accessible by the user, loads HTML popup windows with some other flash contents in it. It still works fine on

  • Problem with posting - PR05 - urgent

    Dear All, When I try to post particular trip using PRFI , it’s not working and giving the below Error Message ‘No vendor found for this selection’ But when I cross check FK02/FK03 for the employee No which I am posting, the data exists already. Reque

  • Wrapper web service for incompatible web service.

    Hey Experts, I'm stuck in a grind! I have a web service that is not compatible with Visual Composer (shows up as "Not Supported" when consumed into VC). I think this maybe due to the fact that the web service return structure is nested and complex. S

  • Added webutil object group with JDAPI - adjust the webutil block sequence ?

    Hi all, I'm using the JDAPI to subclass in the webutil object group into Forms in an application. Annoyingly, the webutil block becomes the first block on the Form - which means on some Forms it displays on startup. Is there anyway (programmatically