List in prepared statement

Hi there!
How can I make this Prepared Statement:
"select * from table where id_table in ?"
the possible values for the ? should be something like this: (1, 2, 4, 7).
Which method should I use to set the ?????
Thanks in advance

Look here:
http://forum.java.sun.com/thread.jsp?forum=48&thread=221725&start=8
That was my advice which the questioner choose.
But please read the entire thread - maybe there are more good ideas hidden there.

Similar Messages

  • Disadvantages in prepared statement

    hi
    i could not tell the answer for the following question in my interview can u pleae tell me the answer for this question
    one of the disadvantages with prepared statement in jdbc?

    I have no idea what WorkForFood is talking about.Sorry, perhaps an example will help clarify:
    Using a PreparedStatement using two replacement parameters:
    String sql = "SELECT COL1 FROM MYTABLE WHERE COL1 = ? AND COL2 = ?";
    ps.setSetring("WORK");
    ps.setString("FORFOOD");Contrasted against a Statement using literals:
    "SELECT COL1 FROM MYTABLE WHERE COL1 = 'WORK' AND COL2 = 'FORFOOD'";When you execute these two queries, they can generate different explain plans, for example the Statement may use an index while the PreparedStatement may attempt a full table scan. The optimizer is choosing a more efficient explain plan for the Statement because it has more information on which to make a decision (the literal values). A full table scan will be significantly slower then using an index to return the same results. In some databases, you can provide hints, but in some cases, the only way to get this query to use an index is to provide the actual values WORK and FORFOOD in the query itself. When using literals rather then replacement parameters it should be more efficient to use Statement then PreparedStatement (see jschell's list #1). So, in these cases, you should use a Statement rather then a PreparedStatement to get best performance from your query. And again, this issue comes up very infrequently but can be quite debilitating to an applications performance when it does occur.

  • Using "IN" clause in prepared statement

    I need to set string for an IN clause in a sql query. But I am not able to get the format in which the string to be set.
    TABLENAME.COLUMNAME IN ( ? )
    preparedStatement.setString( 'A' , 'B' );
    It doesn't works
    help me out?

    I need to set string for an IN clause in a sql query.
    But I am not able to get the format in which the
    string to be set.
    TABLENAME.COLUMNAME IN ( ? )
    preparedStatement.setString( 'A' , 'B' );
    It doesn't works
    help me out?You can't do that; the "?" in the SQL for a prepared statement is not used for arbitrary string replacement. Each "?" has to correspond to a data value that will be bound later.
    In other words, you can do:
    "SELECT * FROM tablename WHERE keyvalue in (?, ?, ?)";
    pstmt.setString(1,"A");
    pstmt.setString(2,"A");
    pstmt.setString(3,"A");There is no way to have a single "?" replaced by a variable-length list.

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

  • 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

  • Help changing to prepared statements for mysqli

    I am trying to change previously working php pages from mysql to mysqli using prepared statements.
    I am having problems with an error message.
    Basically the page I have just changed produces a set of database results depending on list menu and check box criteria from user input. I run 2 queries, one to find the total number of records, and the other to retrieve the required subset for pagination. All works fine. However if there are no actual results found from the requested input my php script then uses an includes file which basically runs the same 2 queries but with the user criteria narrowed down so that similar options are presented to the user. This is where my problem lies, for some unknown to me reason the second set of queries is producing no results and an error:
    'Attempt to read a row while there is no result set associated with the statement'
    If I run the second set of queries without running the first set then the second set works fine so I know that it is not the statements themselves but something in my new code. How can the first set of queries be affecting the results of the second set?
    Here is the code below which produces the first 2 queries that work, and below it the same code for the second 2 queries (which is from an 'Includes' file and is the same code exactly except the EXPECTED parameters $expected have been narrowed down in the expected array and list of params for binding).
    //list of possible field input by user
    $expected = array('location'   => 'text',
                      'type' => 'text',
                      'beds' => 'text',
                      'price' => 'text',
    'nbuild'     => 'int',
    'resale'     => 'int',
    'coastal'    => 'int',
    'seaview'    => 'int',
    'rural'      => 'int',
    'golf'       => 'int',
    'ppool'      => 'int',
    'comp'       => 'int',                            
    'garden'     => 'int',
    'terrace'    => 'int',
    'aircon'     => 'int',
    'heating'    => 'int',
    'garage'     => 'int',
    'telephone'  => 'int',
    'furnished'  => 'int',
    'internet'   => 'int',
    'dpaid'      => 'int',
    'propid'     => 'text');
    define('SHOWMAX', 10);
    // prepare SQL to get total records
    $getTotal = 'SELECT COUNT(*) FROM detailstable JOIN newloctable ON detailstable.location=newloctable.newlocid JOIN typetable ON detailstable.type=typetable.typeid JOIN pricetable ON detailstable.price=pricetable.priceid JOIN bedtable ON detailstable.beds=bedtable.bedid JOIN photossale ON detailstable.detailsid=photossale.propsaleid ';
    // Set a flag to indicate whether the query has a WHERE clause
    $where = false;
    // Loop through the associatiave array of expected search values
    foreach ($expected as $var => $type) {
      if (isset($_GET[$var])) {
        $value = trim(urldecode($_GET[$var]));
        if (!empty($value)) {
          // Check if the value begins with > or <
          // If so, use it as the operator, and extract the value
          if ($value[0] == '>' || $value[0] == '<') {
            $operator = $value[0];
            $value = ltrim(substr($value, 1));
          } elseif (strtolower($type) != 'like') {
            $operator = '=';
          // Check if the WHERE clause has been added yet
          if ($where) {
            $getTotal .= ' AND ';
          } else {
            $getTotal .= ' WHERE ';
            $where = true;
          // Build the SQL query using the right operator and data type
           $type = strtolower($type);
          switch($type) {
            case 'like':
              $getTotal .= "`$var` LIKE ? ";
              break;
            case 'int':
            case 'double':
            case 'date':
              $getTotal .= "`$var` $operator ? ";
              break;
            default:
            $getTotal .= "`$var` = ? ";
    $getTotal .= ' ORDER BY ABS(detailstable.trueprice), bedtable.number, detailstable.propid ASC';
    $stmt = $conn->stmt_init();
    if ($stmt->prepare($getTotal)) {
    $params = array($_GET['location'], $_GET['type'], $_GET['beds'], $_GET['price'], $_GET['nbuild'], $_GET['resale'], $_GET['coastal'], $_GET['seaview'], $_GET['rural'], $_GET['golf'], $_GET['ppool'], $_GET['comp'], $_GET['garden'], $_GET['terrace'],
    $_GET['aircon'], $_GET['heating'], $_GET['garage'], $_GET['telephone'], $_GET['furnished'], $_GET['internet'], $_GET['dpaid'], $_GET['propid']);
    $params = array_filter($params);
    $params = array_values($params);
    if (!empty($params)) {
                $types = '';
                foreach($params as $param) {
                    // set param type
                    if (is_string($param)) {
                        $types .= 's';  // strings
                    } else if (is_int($param)) {
                        $types .= 'i';  // integer
                    } else if (is_float($param)) {
                        $types .= 'd';  // double
                    } else {
                        $types .= 'b';  // default: blob and unknown types
                $bind_names[] = $types;
                for ($i=0; $i<count($params);$i++) {
                    $bind_name = 'bind' . $i;      
                    $$bind_name = $params[$i];     
    $bind_names[] = &$$bind_name;  
    call_user_func_array(array(&$stmt,'bind_param'),$bind_names);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($total);
    $stmt->fetch();
    // sort paging
    $totalRecords = $total;
    $stmt->free_result();
    $stmt->close();
    // check that there is at least 1 result and if there is do the second part of the search
    // if there is no result then I skip this second bit of code
    if($totalRecords > '0') {
    // check current page
    if (isset($_GET['curPage'])) {
    $curPage = $_GET['curPage'];
    } else {
    $curPage = 0;
    // calculate the start row of the subset
    $startRow = $curPage * SHOWMAX;        
    $sql = "SELECT DISTINCT detailsid, trueprice, reduced, offers, `desc`, `propid`, `bathrooms`, `location`, `type`, `price`, `beds`, photossale.photo1, newloctable.newloc,   typetable.style, bedtable.`number` FROM detailstable JOIN newloctable ON detailstable.location=newloctable.newlocid JOIN typetable ON detailstable.type=typetable.typeid JOIN pricetable ON detailstable.price=pricetable.priceid JOIN bedtable ON detailstable.beds=bedtable.bedid JOIN photossale ON detailstable.detailsid=photossale.propsaleid ";
    // Set a flag to indicate whether the query has a WHERE clause
    $where = false;
    // Loop through the associatiave array of expected search values
    foreach ($expected as $var => $type) {
      if (isset($_GET[$var])) {
        $value = trim(urldecode($_GET[$var]));
        if (!empty($value)) {
          // Check if the value begins with > or <
          // If so, use it as the operator, and extract the value
          if ($value[0] == '>' || $value[0] == '<') {
            $operator = $value[0];
            $value = ltrim(substr($value, 1));
          } elseif (strtolower($type) != 'like') {
            $operator = '=';
          // Check if the WHERE clause has been added yet
          if ($where) {
            $sql .= ' AND ';
          } else {
            $sql .= ' WHERE ';
            $where = true;
          // Build the SQL query using the right operator and data type
           $type = strtolower($type);
          switch($type) {
            case 'like':
              $sql .= "`$var` LIKE  ? ";
              break;
            case 'int':
            case 'double':
            case 'date':
              $sql .= "`$var` $operator ? ";
              break;
            default:
            $sql .= "`$var` = ? ";
    $sql .= " ORDER BY ABS(detailstable.trueprice), bedtable.number, detailstable.propid ASC LIMIT $startRow," . SHOWMAX;
    $stmt = $conn->stmt_init();
    if ($stmt->prepare($sql)) {
    $nextparams = $params;
    if (!empty($nextparams)) {
                $nexttypes = '';
    foreach($nextparams as $nextparam) {
                    // set param type
                    if (is_string($nextparam)) {
    $nexttypes .= 's';  // strings
                    } else if (is_int($nextparam)) {
    $nexttypes .= 'i';  // integer
                    } else if (is_float($nextparam)) {
    $nexttypes .= 'd';  // double
                    } else {
    $nexttypes .= 'b';  // default: blob and unknown types
                $newbind_names[] = $nexttypes;
                for ($i=0; $i<count($nextparams);$i++) {
    $newbind_name = 'bind' . $i;      
    $$newbind_name = $nextparams[$i];
    $newbind_names[] = &$$newbind_name;
    call_user_func_array(array(&$stmt,'bind_param'),$newbind_names);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($detailsid, $trueprice, $reduced, $offers, $desc, $propid, $bathrooms, $location, $type, $price, $beds, $photo1, $newloc, $style, $bednumber);
    $numRows = $stmt->num_rows;
    If a result was found in the part that checks the numbers of records then the second query is run and displayed using : while ($stmt->fetch()) { ...... to display the results and then I use $stmt->free_result();
    $stmt->close();
    All fine no problems.
    If the first query did not find a result then the second query is skipped and instead the script then uses a php includes file with exactly the same script as above except the expected params are narrowed as below: THIS IS WHEN I GET NO RESULTS – when I do expect to get a result) AND AN ERROR OF :
    Attempt to read a row while there is no result set associated with the statement.
    Yet if I run the includes file and skip the whole of the above code the code in the includes file find the result no problem. Anyway code below:
    $expected = array('location'   => 'text',
                      'type' => 'text',
                      'beds' => 'text',
                      'price' => 'text',
    'dpaid'      => 'int',
    'propid'     => 'text');
    define('SHOWMAX', 10);
    // prepare SQL to get total records
    $getTotal = 'SELECT COUNT(*) FROM detailstable JOIN newloctable ON detailstable.location=newloctable.newlocid JOIN typetable ON detailstable.type=typetable.typeid JOIN pricetable ON detailstable.price=pricetable.priceid JOIN bedtable ON detailstable.beds=bedtable.bedid JOIN photossale ON detailstable.detailsid=photossale.propsaleid ';
    // Set a flag to indicate whether the query has a WHERE clause
    $where = false;
    // Loop through the associatiave array of expected search values
    foreach ($expected as $var => $type) {
      if (isset($_GET[$var])) {
        $value = trim(urldecode($_GET[$var]));
        if (!empty($value)) {
          // Check if the value begins with > or <
          // If so, use it as the operator, and extract the value
          if ($value[0] == '>' || $value[0] == '<') {
            $operator = $value[0];
            $value = ltrim(substr($value, 1));
          } elseif (strtolower($type) != 'like') {
            $operator = '=';
          // Check if the WHERE clause has been added yet
          if ($where) {
            $getTotal .= ' AND ';
          } else {
            $getTotal .= ' WHERE ';
            $where = true;
          // Build the SQL query using the right operator and data type
           $type = strtolower($type);
          switch($type) {
            case 'like':
              $getTotal .= "`$var` LIKE ? ";
              break;
            case 'int':
            case 'double':
            case 'date':
              $getTotal .= "`$var` $operator ? ";
              break;
            default:
            $getTotal .= "`$var` = ? ";
    $getTotal .= ' ORDER BY ABS(detailstable.trueprice), bedtable.number, detailstable.propid ASC';
    $stmt = $conn->stmt_init();
    if ($stmt->prepare($getTotal)) {
    $params = array($_GET['location'], $_GET['type'], $_GET['beds'], $_GET['price'], $_GET['dpaid'], $_GET['propid']);
    $params = array_filter($params);
    $params = array_values($params);
    if (!empty($params)) {
                $types = '';
                foreach($params as $param) {
                    // set param type
                    if (is_string($param)) {
                        $types .= 's';  // strings
                    } else if (is_int($param)) {
                        $types .= 'i';  // integer
                    } else if (is_float($param)) {
                        $types .= 'd';  // double
                    } else {
                        $types .= 'b';  // default: blob and unknown types
                $bind_names[] = $types;
                for ($i=0; $i<count($params);$i++) {
                    $bind_name = 'bind' . $i;      
                    $$bind_name = $params[$i];     
    $bind_names[] = &$$bind_name;  
    call_user_func_array(array(&$stmt,'bind_param'),$bind_names);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($total);
    $stmt->fetch();
    // sort paging
    $totalRecords2 = $total;
    echo $stmt->error;
    $stmt->free_result();
    $stmt->close();
    // there is a result get the subset
    if($totalRecords2 > '0') {
    // check current page
    if (isset($_GET['curPage'])) {
    $curPage = $_GET['curPage'];
    } else {
    $curPage = 0;
    // calculate the start row of the subset
    $startRow = $curPage * SHOWMAX;        
    $sql = "SELECT DISTINCT detailsid, trueprice, reduced, offers, `desc`, `propid`, `bathrooms`, `location`, `type`, `price`, `beds`, photossale.photo1, newloctable.newloc,   typetable.style, bedtable.`number` FROM detailstable JOIN newloctable ON detailstable.location=newloctable.newlocid JOIN typetable ON detailstable.type=typetable.typeid JOIN pricetable ON detailstable.price=pricetable.priceid JOIN bedtable ON detailstable.beds=bedtable.bedid JOIN photossale ON detailstable.detailsid=photossale.propsaleid ";
    // Set a flag to indicate whether the query has a WHERE clause
    $where = false;
    // Loop through the associatiave array of expected search values
    foreach ($expected as $var => $type) {
      if (isset($_GET[$var])) {
        $value = trim(urldecode($_GET[$var]));
        if (!empty($value)) {
          // Check if the value begins with > or <
          // If so, use it as the operator, and extract the value
          if ($value[0] == '>' || $value[0] == '<') {
            $operator = $value[0];
            $value = ltrim(substr($value, 1));
          } elseif (strtolower($type) != 'like') {
            $operator = '=';
          // Check if the WHERE clause has been added yet
          if ($where) {
            $sql .= ' AND ';
          } else {
            $sql .= ' WHERE ';
            $where = true;
          // Build the SQL query using the right operator and data type
           $type = strtolower($type);
          switch($type) {
            case 'like':
              $sql .= "`$var` LIKE  ? ";
              break;
            case 'int':
            case 'double':
            case 'date':
              $sql .= "`$var` $operator ? ";
              break;
            default:
            $sql .= "`$var` = ? ";
    $sql .= " ORDER BY ABS(detailstable.trueprice), bedtable.number, detailstable.propid ASC LIMIT $startRow," . SHOWMAX;
    $stmt = $conn->stmt_init();
    if ($stmt->prepare($sql)) {
    $nextparams = $params;
    if (!empty($nextparams)) {
                $nexttypes = '';
    foreach($nextparams as $nextparam) {
                    // set param type
                    if (is_string($nextparam)) {
    $nexttypes .= 's';  // strings
                    } else if (is_int($nextparam)) {
    $nexttypes .= 'i';  // integer
                    } else if (is_float($nextparam)) {
    $nexttypes .= 'd';  // double
                    } else {
    $nexttypes .= 'b';  // default: blob and unknown types
                $newbind_names[] = $nexttypes;
                for ($i=0; $i<count($nextparams);$i++) {
    $newbind_name = 'bind' . $i;      
    $$newbind_name = $nextparams[$i];
    $newbind_names[] = &$$newbind_name;
    call_user_func_array(array(&$stmt,'bind_param'),$newbind_names);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($detailsid, $trueprice, $reduced, $offers, $desc, $propid, $bathrooms, $location, $type, $price, $beds, $photo1, $newloc, $style, $bednumber);
    $numRows = $stmt->num_rows;
    Again here I would then display the results before closing and freeing the stmt or display a message to say there were no results found from the criteria. But instead I get the error message and echoing the value of $totalRecords2 is empty.
    I have been pulling my hair out for days and days over this and as it is one of the first pages I am converting from mysql to mysqli I wonder if I am missing something very obvious to someone with more experience with the code.  I will be very grateful for any help, thank you in advance.

    You have intel graphics, that means the graphics cannot be upgraded.
    Welcome to the Toshiba user forums.
    For those of you who do not know what a user forum is, it is a community of users who volunteer time to help other users. Anyone can participate. It's 100% voluntary.
    Being super active is never a requirement

  • How to use in clause with variable elements with a prepared statement?

    Is there any way to use a prepared statement for a query which incorporates an in clause with unknown number of elements in the list?
    null

    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Iraj ():
    Is there any way to use a prepared statement for a query which incorporates an in clause with unknown number of elements in the list?<HR></BLOCKQUOTE>
    Sorry, can't be done. The PreparedStatement is precomplied, so you can't have variable number of params or unknown number of elements in a list.

  • Prepared statement order by

    I have a problem with order by status in a prepared statement. The list is generated with no order by. However I can not find the error in code.
    Tomcat log print out the query as "com.mysql.jdbc.ServerPreparedStatement[1] - SELECT * FROM tm_game_tables order by 'name';"
    I call the bean from website with:
    <%
    ilia.admin.tm.ListTableBean ltb = new ilia.admin.tm.ListTableBean();
    ltb.setTm_order("name");
    %>
    <table>
    <%=ltb.getList()%>
    </table>Bean code:
    package ilia.admin.tm;
    import ilia.*;
    import java.sql.*;
    import java.io.*;
    import java.util.*;
    public class ListTableBean {
         String tm_order = "";
         public String getTm_order() {
              return tm_order;
         public void setTm_order(String tm_order) {
              this.tm_order = tm_order.trim();
         ConnectionPool pool = new ConnectionPool();
         Connection con = null;
         public String getList() throws ClassNotFoundException{
              String rt = ""; // String to return
              try{
                   con = pool.getConnection();
                   Object[] tm_type_array = {"Real Money", "Play Money"};
                   Object[] tm_status_array = {"Open", "Closed", "Maintance"};
                   PreparedStatement pStmt = con.prepareStatement("SELECT * FROM tm_game_tables order by ?;");
                   pStmt.setString(1, tm_order);
              System.out.println(pStmt);
                   ResultSet rs = pStmt.executeQuery();
                   if(!rs.next()){
                        rt = "";
                   else do {
                        rt = rt + "<tr><td>" + rs.getInt("table_id") + "</td>";
                        rt = rt + "<td>" + rs.getString("name") + "</td>";
                        rt = rt + "<td>" + tm_type_array[rs.getInt("type")] + "</td>";
                        rt = rt + "<td>$" + rs.getDouble("buy_in") + "</td>";
                        rt = rt + "<td>" + rs.getDouble("rake") + "%</td>";
                        rt = rt + "<td>" + tm_status_array[rs.getInt("status")] + "</td>";
                        rt = rt + "<td>" + rs.getString("url_background_image") + "</td>";
                        rt = rt + "<td>" + rs.getString("password") + "</td>";
                        rt = rt + "<td>" + rs.getString("update") + "</td>";
                        rt = rt + "<td>" + rs.getString("user") + "</td></tr>";
                   } while(rs.next());
                   pStmt = null;
                   rs = null;
              catch(Exception exp){
                   System.out.println("Exception: "+ exp);
              finally{
                   pool.putConnection(con);
              return rt;
    }If I test the query as per logs in mysql prompt I get the order by I want,
    Regards
    Andreas

    Still don't order them:
    Print out same query in tomcat log.
    Bean is now:
    package ilia.admin.tm;
    import ilia.*;
    import java.sql.*;
    import java.io.*;
    import java.util.*;
    public class ListTableBean {
         String tm_order = "";
         public String getTm_order() {
              return tm_order;
         public void setTm_order(String tm_order) {
              this.tm_order = tm_order.trim();
         ConnectionPool pool = new ConnectionPool();
         Connection con = null;
         public String getList() throws ClassNotFoundException{
              String rt = ""; // String to return
              try{
                   con = pool.getConnection();
                   Object[] tm_type_array = {"Real Money", "Play Money"};
                   Object[] tm_status_array = {"Open", "Closed", "Maintance"};
                   PreparedStatement pStmt = con.prepareStatement("SELECT * FROM tm_game_tables order by ?;");
                   pStmt.setString(1, tm_order);
                   ResultSet rs = pStmt.executeQuery();
              System.out.println(pStmt);
                   if(!rs.next()){
                        rt = "";
                   else do {
                        rt = rt + "<tr><td>" + rs.getInt("table_id") + "</td>";
                        rt = rt + "<td>" + rs.getString("name") + "</td>";
                        rt = rt + "<td>" + tm_type_array[rs.getInt("type")] + "</td>";
                        rt = rt + "<td>$" + rs.getDouble("buy_in") + "</td>";
                        rt = rt + "<td>" + rs.getDouble("rake") + "%</td>";
                        rt = rt + "<td>" + tm_status_array[rs.getInt("status")] + "</td>";
                        rt = rt + "<td>" + rs.getString("url_background_image") + "</td>";
                        rt = rt + "<td>" + rs.getString("password") + "</td>";
                        rt = rt + "<td>" + rs.getString("update") + "</td>";
                        rt = rt + "<td>" + rs.getString("user") + "</td></tr>";
                   } while(rs.next());
                   pStmt = null;
                   rs = null;
              catch(Exception exp){
                   System.out.println("Exception: "+ exp);
              finally{
                   pool.putConnection(con);
              return rt;
    }However if I change ststement to "PreparedStatement pStmt = con.prepareStatement("SELECT * FROM tm_game_tables order by " + tm_order + ";");" as earlier posted wrote I get the order by. However I think that is incorrect prepared statement standard, isn't it?
    Regards
    Andreas

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

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

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

  • Use of Prepared Statement in adf

    Hi Experts,
    I am confused with the Use of prepared statement in adf.
    My use case is ,
    I have to update a table from every page in my application under certain conditions.
    My question is ,
    whether I have to create the VO iterator binding in every page and by calling the createinsert and insert the data in to the table or
    use a common method in the Application module impl
    which is using a prepared statement,(which is not even creating the ViewObject ) like
    PreparedStatement st = null;
    String sql = "INSERT INTO hr.departments (DEPARTMENT_ID,    DEPARTMENT_NAME,   MANAGER_ID,   LOCATION_ID) VALUES (seq,?,?,?)";
                st=getDBTransaction().createPreparedStatement(sql,0);
                st.setString(1, name);
                st.setString(2, mgr_id);
                st.setString(3, Loc_id);
                st.execute();
    getDBTransaction().commit();which is the best approach?
    Studio Edition Version 11.1.1.2.0
    Ranjith

    Ranjith,
    Without further understanding the use case, there's not really much difference between the two approaches. In both cases, you'd have a binding in the page definition (either an iterator binding for the VO or a method binding for the AM service method). Both will use bind variables. The main difference I can see is that, depending on how you have configured your AM pooling settings, the VO method will incur fewer parses in the DB because the AM will cache prepared statements for you.
    John

  • Proving prepared statements are being reused

    How can I prove that a prepared statement from a JDBC driver is being reused / pooled ?
    What essentially I want to do is to have prepared statements reused to reduce hard parsing ... but I also need to prove that the statements are being reused. If I query the statement in V$SQLAREA, the column PARSE_CALLS does not seem to be distinguish between hard parse and soft parse:
    http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96536/ch3204.htm#1126299
    I am only interested for now in proving the just ONE statement is being reused ... which mean that the number of hard parses is very low compared to the number of soft parses for that ONE statement.
    Regards,
    jms
    Message was edited by:
    jms

    Hi,
    No, parse calls is all soft and hard parse together. What you would see, if used absolutely correctly, would be 1 hard parse per session and many executions.
    But since v$sql is obviously not linked to v$session other than at the time of exection, you see the aggregated parse calls and executions for each cursor. So what you should see is parse calls go up relatively slowly to the number of exections.
    However, you can see soft and hard parses using the v$sesstat and v$statname views so you can see soft and hard parses on a session by session basis, be these are again aggregated, so you can't see soft / hard counts per cursor, only the total for a session.
    What I see a lot of the time is they don't get it quite right, so hard parses is low but soft parses are high, so they are still parsing when they don't need to, but at least they are binding and using shareable SQL, which is a step in the right direction.
    When I say 'they', it is a generic reference to all Java/.Nyet programmers writing front end code where they just don't 'get' parsing and binding because it's just too complicated and hey, SQL Server isn't like this...!
    HTH
    Chris

  • 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

  • How do I handle NULL returns from prepared statement?

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

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

  • Connection/ResultSets/Prepared Statement opening and closing

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

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

  • Pass table name as parameter in prepared Statement

    Can I pass table name as parameter in prepared Statement
    for example
    select * from ? where name =?
    when i use setString method for passing parameters this method append single colon before and after of this parameter but table name should be send with out colon as SQL Spec.
    I have another way to make sql query in programing but i have a case where i have limitation of that thing so please tell me is it possible with prepared Statment SetXXx methods or not ?
    Thanks
    Haroon Idrees.

    haroonob wrote:
    I know ? is use for data only my question is this way to pass table name as parameterI assume you mean "how can I do it?" As I have already answered "is this the way?" with no.
    Well, I would say (ugly as it is) String concatenation, or stored procedures.

Maybe you are looking for

  • Bridge Output non existent

    Hi, Just got Photoshop CS5 and when I went to try to make a photo gallery I found that my Output window (where all the photogallery options are) is not there just a grey box where the options should be.  I know what it should look like after watching

  • Trace level="1" type="T" -no interface action for sender or receiver found

    Hi Experts, I try to integrate PI and abap 7.0 using XI adapter (feel doubts about type). RWB and SXMB_MONI at PI side show that test message was successfully sent. But I cant see it in DQ http://cnh.com/XI/SDIIOC01/RCVR</Trace>   <Trace level="1" ty

  • Zen 8Gb freezing on res

    I used ZenCast to get a bunch of podcasts from NPR and transferred them to my Zen 8Gb. These files when transferred show up under the Video menu after transfer. Whenever the unit shuts down after I've paused it (either idle timeout or deliberate shut

  • Default username and password for BPEL Console

    What is the default username and password for BPEL Console?

  • QUICK ACCESS TOOLBAR WONT WORK

    I am not able to scroll thru the commands with FM7.2p158 in Windows 7 Pro. You can see the button go in, it just does not make the toolbar scroll to the next line of tools? please help. Any way to get around this? is/are there some other tool to get