Prepared Statement - Help pl

Hi!
Is there any disadvantage in using a Prepared statement to insert records in to the database.What is the difference in using Prepared Statement compared to Statement.Any disadavantage?I know the advantage of using Prepared statement where by I can insert values with special characters.Any disadavantage of using Prepared statement regularly?Please explain.Thanks

hello all, i like the statement that some of u guys posting here..
i have a puzzle here, if i have more than one query to table, lets say 3rd query are depends on result of 2nd query which taken from 1st query result.
should i use prepared statement instead of statement? can we say that using of prepared statement can make our query result faster than using statement??
i have a function here which goes well when using statement st,
public void getMainlevelBcat(String loggedbizid){
String query = " SELECT DISTINCT category2.mainlevel FROM bizcategory2, category2 "+
" WHERE bizcategory2.catid = category2.catid "+
" AND bizcategory2.bizid ='"+loggedbizid+"' ";
try {
st = con.createStatement();
rs =st.executeQuery(query);
catch (SQLException e) {
System.out.println(e.getMessage());
can anybody chance it to new function using prepared statement??

Similar Messages

  • Prepared statement help... pls...

    hey all... need help... this prepared statement is driving me mad... keeps throwing an error in my servlet.... can somebody pls help
         PreparedStatement updateWiki = con.prepareStatement("UPDATE sportinfo SET pageinfo,parent = (?,?) WHERE sport LIKE ? ");
              updateWiki.setString(1, wikipage);
              updateWiki.setString(2, parent);
              updateWiki.setString(3, sport);
              updateWiki.executeUpdate();
    am i missing something???
    thanks keith

    1. What is the error? Please post it.
    2. Try using the query like:
    UPDATE sportinfo SET pageinfo=?,parent=? WHERE sport LIKE ?
    and see if it still fails.

  • Prepared statement help

    Hello all!
    I am trying to get this prepared statement to work but am getting an error that I cant understand.
    Basically I have a class file that the ps resides in. I am calling the ps from a jsp.
    Here is the code:
    public void recordUsage(String userid, String ipaddress, String page, String filename)
           String insertStatement = "INSERT INTO usageLog(userId,ipAddress, localTime, page, fileName) VALUES(?,?,?,?,?)";
                try
                {   java.util.Date currentDate=new java.util.Date();//Create a date object for the timestamp
                    java.sql.Timestamp ts=new java.sql.Timestamp(currentDate.getTime());//Create the timestamp from the above date object.
                    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                    objConn = java.sql.DriverManager.getConnection("jdbc:odbc:sensorWeek","","");
                    PreparedStatement ps = objConn.prepareStatement(insertStatement);
                    ps.setString(1, userid);
                    ps.setString(2, ipaddress);
                    ps.setTimestamp(3, ts);
                    ps.setString(4, page);
                    ps.setString(5, filename);
                    ps.executeUpdate();
                    objConn.commit();
                    ps.close();
                    objConn.close();
                    System.out.println("recordusage method called");
                catch (SQLException s)
                    System.err.println("DataBase PROBLEM");
                    s.printStackTrace();
                catch (Exception e)
                        System.err.println("Error in recordUsage method");
                        e.printStackTrace();
    }Here is the error generated:(I hate to dump this on you)
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: sensorPac.methodClass.record(Ljava/lang/String;Ljava/lang/String;)V
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:254)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.CertificatesValve.invoke(CertificatesValve.java:246)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2416)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:171)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:601)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:392)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:565)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:619)
         at java.lang.Thread.run(Thread.java:534)
    root cause
    javax.servlet.ServletException: sensorPac.methodClass.record(Ljava/lang/String;Ljava/lang/String;)V
         at org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:536)
         at org.apache.jsp.download_jsp._jspService(download_jsp.java:93)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:137)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:210)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.CertificatesValve.invoke(CertificatesValve.java:246)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2416)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:171)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:601)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:392)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:565)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:619)
         at java.lang.Thread.run(Thread.java:534)
    TIA!!

    And what makes you think that the above code is causing the problem?

  • Required Prepared Statement help

    Consider the following query
    select col2, col3
    from table1
    where col1 = ?
    I can set the bindings for the prepared statement as pStmt.setString(1, value);
    but sometimes I need all the rows in the table therefore the query would be like
    select col2, col3
    from table1
    where col1 = col1
    I would like to set the first query's bindings for the prepared statement to execute like the second one.
    Please do not ask me to create two different queries. I know it is possible to do it and I would appreciate if you can guide me as to how to set the bindings. Thanks,

    Adam Martin wrote:
    Sorry, you cannot treat a bind variable like a bind some of the time and literal SQL text the other part of the time.
    How about something like this:
    select col2, col3
    from table1
    where col1 between ? and ?When you want a specific value, you can say "between 23 and 23" and when you want all values, you can put extremes in like "between -999999 and 999999" so that all rows a returned.
    This is not to say that this is a great approach, but it seems like it would technically allow you to do what you wanted.This is an EXCELLENT approach to confuse the optimizer & produce poor performance.
    I suspect that using the same EXPLAIN PLAN to bring back 1 or and bring back all rows;
    will be suboptimal for a subset of all executions.

  • Prepared Statement help -- cant get it to work :(

    Context initialcontext = new InitialContext();
              DataSource datasource = (DataSource)initialcontext.lookup("java:comp/env/XYZ");
              Connection conn = datasource.getConnection();                
              String UPDATE = "update query with ?s ";
              PreparedStatement pstmt = conn.prepareStatement(UPDATE);
              pstmt.setString(1,title);
              pstmt.setString(2,desc);
              pstmt.setInt(3,1);
              System.out.println("2a");
              pstmt.executeQuery(); ------- STUCK HERE
              System.out.println("2b");                              
              pstmt.close();
    It goes between 2a and 2b and just stops working.. no errors nothing...
    I have been trying to get this working the entire day... with no luck... any suggestions........

    I am familiar with a few dialects of SQL. I've never seen
    UPDATE <tbl> WITH...
    What RDBMS are you using? I just searched the mySQL documentation on the keyword WITH (case sensitive) and found no form of update that uses it.
    The ANSI SQL UPDATE statement takes the form...
    UPDATE <tbl> SET <col> = <value>[, <col> = <value>...]
    Also, you have three calls to setString, but only one ? in your String UPDATE indicating a position for a parameter.
    http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html
    Hope this helps. If there is a form of UPDATE that uses WITH, please provide me with a reference link. I'm supposed to know SQL. :-)

  • Escape Characters - simulate the setString from Prepared Statements

    I would like to see what the value of setString() is for a given prepared statement call.
    Because of reasons that would take me to long to explain that I cannot use preparedstatements with their parameters - I need a way to execute a query like the following:
    String query = "insert into blahtable (somestring) values (\"asdfds\'\s sdsfdasfd \"\& ...\");
    PreparedStatement stmt = connection.prepareStatement(query);
    I know prepared statements can take care of this, but I want to know and write the query as above without the need of prepared statements help for string.
    Below is an example with prepared statement - but not what I want to do
    For example:
    String oddstringwithunusalcharacters = "...";
    String query = "insert into blahtable (somestring) values (?)";
    PreparedStatement stmt = connection.prepareStatement(query);
    stmt.setString(1, oddstringwithunusalcharacters);
    I would like to see what the actual query looks like and what the actual string was passed:
    --> insert into blahtable (something) values ("asdfds\'\s sdsfdasfd \"\& .... ")
    It is not sufficient enough for me to escape quotes and apostrophes because there maybe other unusual characters that I do not know of since the string is passed by an unknown source.
    Thank you in advance

    PreparedStatements actually doesn't escape quotes. It basically precompiles statements in the DB and only passes the values to the DB.
    But if you're using a plain vanilla SQL statement where you quote the string with a single quote ' then you need to escape all occurrences of exactly the same single quote ' in the actual String value. If you for example quote the string with an apostrophe ` then you just need to escape all occurrences of exactly the same apostrophe ` in the actual String value. And so on. It is nothing more than logical, is it?

  • Beginner question about prepared statements...PLEASE help! :-)

    First let me say thanks for the assistance. This is probably really easy to do, but I'm new to JSP and can't seem to figure it out.
    I want to dynamically populate a table that shows whether a particular person has an appointment at a given date and time with a user. To do this, I want to query the MySQL database for the lastname of the person with the appointment that occurs with the user at the year, month, date, and time, in question.
    THE CODE BELOW DOESN'T WORK (obviously) BUT SOMEWHAT ILLUSTRATES WHAT I'M TRYING TO ACCOMPLISH:
    <%
    Driver DriverTestRecordSet = (Driver)Class.forName(MM_website_DRIVER).newInstance();
    Connection ConnTestRecordSet = DriverManager.getConnection(MM_website_STRING,MM_website_USERNAME,MM_website_PASSWORD);
    PreparedStatement StatementTestRecordSet = ConnTestRecordSet.prepareStatement("SELECT lastname FROM appts_pid1 WHERE user_id='<%=(((Recordset1_data = Recordset1.getObject(user_id))==null || Recordset1.wasNull())?"":Recordset1_data)%>' AND year='<%= yy %>' AND month='<%= months[mm] %>' AND date='<%= dates[dd] %>' AND appttime='16:15:00'");
    ResultSet TestRecordSet = StatementTestRecordSet.executeQuery();
    boolean TestRecordSet_isEmpty = !TestRecordSet.next();
    boolean TestRecordSet_hasData = !TestRecordSet_isEmpty;
    Object TestRecordSet_data;
    int TestRecordSet_numRows = 0;
    %>
    The real problem comes in the prepared statement portion. If I build the prepared statement with static values like below, EVERYTHING WORKS GREAT:
    PreparedStatement StatementTestRecordSet = ConnTestRecordSet.prepareStatement("SELECT lastname FROM appts_pid1 WHERE user_id='1' AND year='2002' AND month='October' AND date='31' AND appttime='16:15:00'");
    But when I try to use dynamic values, everything falls apart. It's not that the values aren't defined, I use the user_id, year <%= yy %>, month <%= months[mm] %>, etc. elsewhere on the page with no problems. It's just that I can't figure out how to use these dynamic values within the prepared statement.
    Thanks for reading this far and thanks in advance for the help!!!!

    Hi PhineasGage
    You are little bit wrong in your
    your preparedStatement.
    Expression tag within scriptlet tag is invalid.
    Whenever you are appending the statement with
    expression tag, append it with "+" and remove
    expression tag.
    Hopefully it will work
    ThanksThanks for the response!
    I know that the expression tag within scriptlet tag is invalid. I just need a workaround for what I want to do.
    I'm unclear what you mean by "Whenever you are appending the statement with expression tag, append it with a "+" and remove expression tag".
    Could you give an example?
    In the meantime, I've been trying to digest the docs on prepared statements and have changed the code to look like:
    PreparedStatement StatementTestRecordSet = ConnTestRecordSet.prepareStatement("SELECT lastname FROM appts_pid1 WHERE user_id= ? AND year= ? AND month= ? AND date= ? AND appttime='13:15:00'");
    StatementTestRecordSet.setInt(1,1);
    StatementTestRecordSet.setInt(2,2002);
    StatementTestRecordSet.setString(3,"October");
    StatementTestRecordSet.setInt(4,31);
    Again, WITH THE STATIC VALUES, THIS WORKS FINE...but when I try to use expressions or variables like below, things don't work:
    StatementTestRecordSet.setInt(2,<%= yy %>);
    Obviously, I'm doing something wrong, but there has to be a way to use variables within the prepared statement.
    ALSO, the values are being passed to this page via URL in the form:
    samplepage?user_id=1&year=2002&month=October&date=31
    Based upon this information, is there another way (outside of stored procedures in the db) to do what I want to do? I'm open to ideas.

  • Dynamic Prepared statement--pls help

    I need to create a prepared statement where i do not know how many parameters( or arguments i.e " ? ") will be passed. The arguments are decided dynamically while runtime...as in i may pass only a single argument or many.
    example:
    select * from employee_table where employee_id in (?,?....)
    in the above query i may only one employee_id or may be more than one.This is decided during run time.I do not want to run a for loop for the number of employee is as this will cause performance issue. can anybody please tell me how these arguments can be generated dynamically
    thanks 4 ur help in advance

    When will you know the emp.Id ?
    Reason is Once you get the emp.Id at runtime means you can assign this id to string variable using the comma separator and assigned this string to the query.
    Example
    String listOfEmpId = "e11,ee23,e55..."; and then use this variable in the query.

  • 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

  • Can any body Help me to prepare statement

    I want to provide dynamic table name for preparestatement that i just pass table name every time and it pass me total number in that table.
    I create this prepare statement
    PreparedStatement prepStmt=conn_.prepareStatement("select count(*) Total from ?");
    prepStmt.setString(1,"new");
    but it is giving error
    [JDBC SQL Server Driver] Line 1: Incorrect syntax near 'new'.
    Any body can help me??
    I will appreciate.

    In PreparedStatement, the setString method adds quotes at the start and at the end of your String.
    So your request :
    select count(*) Total from ?
    is interpreted :
    select count(*) Total from 'new'
    One possible solution is to pass your tablename parameter directly in the precompiled request :
    String myTableName = "new";
    PreparedStatement prepStmt=conn_.prepareStatement("select count(*) Total from "+myTableName);
    In your database, you will store as many precompiled Statement as you will call this method with different parameters.
    Hope it helps !

  • How to use prepared statement - For Everyone Help

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

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

  • Prepared statement - setDate(index, sql.Date, Cal) Help!

    Hi everyone, I'm creating a form to query an Oracle table. I'm setting up the search criteria which includes a start and end date. (in this example I've just used the start date)
    I get all the search parameters into my JSP and I created the following Calendar objects:
    // Calendar creation
    Calendar startCal = Calendar.getInstance();
    startCal.set(start_year, start_month, start_day, start_hour, start_minute);
    Calendar endCal = Calendar.getInstance();
    endCal.set(end_year, end_month, end_day, end_hour, end_minute);
    //define a sql.Date value for start and end date
    java.sql.Date startDate = null;
    java.sql.Date endDate = null;I then create a string that contains my SQL statement:
    String sqlStmt = "select dateValue, value3 from someTable where dateValue >= ? and value2 = ?";In my Prepared Statement I pass in the following information:
    ps = c.prepareStatement(sqlStmt);
    ps.setDate(1, startDate, startCal);
    ps.setString(2, searchValue);My question is the following - I define the hour and minute in my Cal object - will that information get passed into my "startDate" sql.Date object? According to the API it should work (at least that's my understading of it):
    http://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.html#setDate(int,%20java.sql.Date,%20java.util.Calendar)
    My search does not blow up or report any errors but it never finds a match - even when I put in parameters that I know are a match.
    Any feedback is appreciated.

    I think I got it. my java.sql.Date can't be null.
    java.sql.Date startDate = null;
    java.sql.Date endDate = null;needs to be:
    java.util.Date startCalendarDate = startCal.getTime();
    java.util.Date endCalendarDate = endCal.getTime();
    java.sql.Date startDate = new java.sql.Date(startCalendarDate.getTime());
    java.sql.Date endDate = new java.sql.Date(endCalendarDate.getTime());

  • Help for prepared statement

    hi,
    I want to usefollowing sql statement by preparedstatment
    select * from tbl_PreServiceManager where (trunc(Activation_Date+30)<trunc(Sysdate) or counter > 0) and CPS<>'FDE'";{code}
    to convert it to prepared statement i did following
    {code}String query="select * from tbl_Pre where (trunc(Activation_Date+30)<trunc(Sysdate) or counter >?) and CPS<>?;"
                pstmt = conn.prepareStatement( query );
                pstmt.setInt(1,0);
                pstmt.setString(2,"FDE");
                rset = pstmt.executeQuery();
    {code}
    but how i manage activation_date with trunc function, infact activation_date field is datetime and i only want to campare date.
    Thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    EG:
    datepart (dp):
    dd ->  day         ->  1-31
    dy ->  day of year ->  1-366
    hh ->  hour        ->  0-23
    mi ->  minute      ->  0-59
    mm ->  month       ->  1-12
    qq ->  quarter     ->  1-4
    ss ->  second      ->  0-59
    ms ->  millisecond ->  0-999
    wk ->  week        ->  0-53
    dw ->  weekday     ->  1-7(Sun - Mon)
    yy ->  year        ->  1753
    SELECT DATEPART(yy,GETDATE()),
           DATEPART(mm,GETDATE()),
           DATEPART(dy,GETDATE())Output
    2008 | 07 | 28

  • Help with streaming result sets and prepared statements

    hi all
    I create a callable statement that is capable of streaming.
    statement = myConn2.prepareCall("{call graphProc(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}",java.sql.ResultSet.TYPE_FORWARD_ONLY,
    java.sql.ResultSet.CONCUR_READ_ONLY);
    statementOne.setFetchSize(Integer.MIN_VALUE);
    the class that contains the query is instantiated 6 times the first class streams the results beautifully and then when the second
    rs = DatabaseConnect.statementOne.executeQuery();
    is executed I get the following error
    java.sql.SQLException: Can not use streaming results with multiple result statements
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:910)
    at com.mysql.jdbc.MysqlIO.readAllResults(MysqlIO.java:1370)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1688)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3031)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:943)
    at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1049)
    at com.mysql.jdbc.CallableStatement.executeQuery(CallableStatement.java:589)
    the 6 instances are not threaded and the result set is closed before the next query executes is there a solution to this problem it would be greatly appreciated
    thanks a lot
    Brian

    Database resources should have the narrowed scope
    possible. I don't think it's a good idea to use a
    ResultSet in a UI to generate a graph. Load the data
    into an object or data structure inside the method
    that's doing the query and close the ResultSet in a
    finally block. Use the data structure to generate
    the graph.
    It's an example of MVC and layering.
    Ok that is my bad for not elaborating on the finer points sorry, the results are not directly streamed into the graphs from the result set. and are processed in another object and then plotted from there.
    with regards to your statement in the beginning I would like to ask if you think it at least a viable option to create six connections. with that said would you be able to give estimated users using the six connections under full usage.
    just a few thoughts that I want to
    bounce off you if you don't mind. Closing the
    statement would defeat the object of of having a
    callable statement How so? I don't agree with that.
    %again I apologise I assumed that since callable statements inherit from prepared statements that they would have the pre compiled sql statement functionality of prepared statements,well If you consider in the example I'm about to give maybe you will see my point at least with regards to this.
    The statement that I create uses a connection and is created statically at the start of the program, every time I make a call the same statement and thus connection is used, creating a new connection each time takes up time and resources. and as you know every second counts
    thanks for your thoughts
    Brian.

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

Maybe you are looking for