PreparedStatement and LIKE

Can I use LIKE in a preparedStatement?
String selectTwo =
"SELECT zip_code " +
"FROM alk_zip " +
"WHERE zip_code LIKE ? " +
"ORDER BY zip_code";
PreparedStatement stmtTwo = con.prepareStatement( selectTwo );
// loop starts here
stmtTwo.setString( 1, "'" + partial + "%'" );
// that's double-quote single-quote double-quote + partial + double-quote
percent single-quote double-quote
rsTwo = stmtTwo.executeQuery();
// we only want the first match
if ( rsTwo.next() )
ZipCodes.add( rsTwo.getString( 1 ).trim() );
// loop ends here
Does this look correct? I'm not getting any results. If I don't use a
prepared statement and construct the SQL Select every time, I get the
results I'm expecting.

Yep, setString already adds the appropriate quotes to your parameter.
Nils
Eric F wrote:
>
I figured it out.
It should be:
stmtTwo.setString( 1, partial + "%" );
instead of:
stmtTwo.setString( 1, "'" + partial + "%'");
"Eric F" <[email protected]> wrote in message
news:3be17308$[email protected]..
Can I use LIKE in a preparedStatement?
String selectTwo =
"SELECT zip_code " +
"FROM alk_zip " +
"WHERE zip_code LIKE ? " +
"ORDER BY zip_code";
PreparedStatement stmtTwo = con.prepareStatement( selectTwo );
// loop starts here
stmtTwo.setString( 1, "'" + partial + "%'" );
// that's double-quote single-quote double-quote + partial + double-quote
percent single-quote double-quote
rsTwo = stmtTwo.executeQuery();
// we only want the first match
if ( rsTwo.next() )
ZipCodes.add( rsTwo.getString( 1 ).trim() );
// loop ends here
Does this look correct? I'm not getting any results. If I don't use a
prepared statement and construct the SQL Select every time, I get the
results I'm expecting.
============================
[email protected]

Similar Messages

  • PreparedStatements and LIKE clauses

    Hi,
    I've come across a slight problem with PreparedStatements and LIKE clauses. Say I want my query to look something like this:
    SELECT * FROM CONTENT_TABLE WHERE CONTENT LIKE '%test%'If I were to use a PreparedStatement I'd do something like this:
    PreparedStatement searchContent = con.prepareStatement("SELECT * FROM CONTENT_TABLE WHERE CONTENT LIKE ?");
    searchContent.setString(1, queryString);This isn't correct becuase it matches where CONTENT LIKE 'queryString'
    I tried this:
    PreparedStatement searchContent = con.prepareStatement("SELECT * FROM CONTENT_TABLE WHERE CONTENT LIKE '%?%'");
    searchContent.setString(1, queryString);But I get a syntax error in my SQL.
    Is there another way around this?
    Thanks

    just guessing try this:
    PreparedStatement searchContent = con.prepareStatement("SELECT * FROM CONTENT_TABLE WHERE CONTENT LIKE '%?%'");searchContent.setString(1, "%"+queryString+"%");
    This might work, since ? gets replaced by '...', so i am guessing %..% will fit..
    give it a shot, i might be wrong.

  • Using PreparedStatement and the Oracle Error ORA-1000

    Hi,
    I have a question about PreparedStatement objects that is not so simple to explain for me. What I would like to know is: if I use a PreparedStatement following traditional and generic steps:
    1- PreparedStatement pStmt = Connection.prepareStatement(sQuery);
    2- pStmt.setXXX(i,j);
    n - pStmt.setXXX(i,j);
    n+1 - ResultSet rs = pStmt.executeQuery();
    n+2 - while(rs.next()){ ... retrive ResultSet data  ... }
    n+3 - rs.close()
    n+4 - back to point number 2
    and at the end (as you can see in the point numbered n+4), instead of closing the PreparedStatement pStmt using the close() method, I reuse the PreparedStatement pStmt comeing back to the point numebr 2 and setting again all its parameters with new values ... then ... what heppens in the Oracle database ? Has been the cursor (so the mamory area), associated to my PreparedStatement object pStmt, duplicated or is it the same ?
    I know that Java allows you to do this kind of operations with PreparedStatement, and I know that in tha Java Documentation is explained to follow this strategy to optimize the execution time because in this way the same PreparedStatement is precompiled and prepared only once. But if I do a for loop following the steps explained before, after many iterations I have the error "ORA-1000: maximum open cursors exceeded". This error is the reason of my question. Does this error means that it's mandatory to close a PreparedStatement always, otherwise if you reuse it without closing it then the corresponding database cursor will be duplicated ? If it is so, then I think this is a contradiction with official java documentation ...
    I'm using Oracle8i (version 8.1.7) and Oracle JDBC Thin Driver (Windows NT) for use with JDK 1.2.x. Moreover, in my database istance the parameter "maximum open cursor" is equal to 800 ...
    Thank you very much for suggestions :-)

    There is no need to close a prepared statement or its resultset for every iteration.
    After the first iteration in a loop, all subsequent executions of it will close the previous resultset. By adding close() method, you are making one extra costly call to the DB for no reason.
    Following is the sample code.I know what you are saying. In fact at the beginning I wrote my code in the same way of your sample (see the code of my first post at the begin of this page).
    But doing so, after thousand iterations of the loop, I had "Oracle Error ORA-1000 : maximun open cursor exeeded" even if in my database istance the parameter "maximum open cursor" is equal to 8000.
    At this moment in my code, for each iteration, I close the PreparedStatement and in this way I don't have anymore the error :-((
    So it seems that only in theory we can reuse a preparedStatement without closing it. In fact if we see the oracle system table "$open_cursor" (as Konrad Pietzka suggest me) we can find that, for each interation,
    at our line code "rs = pstmt.executeQuery();" correspond a new cursor in the database: this means that for each method "pstmt.executeQuery()" the database open a new cursor and do not use the previous one as it should.
    I posted a question two months ago to search if someone had the same problem (it seems that Konrad Pietzka had the same situation) and was able to explain me what is the cause.
    The only reason I found by myself for this problem, is that probably the Oracle JDBC Thin Driver for Windows NT/2000 has some bugs... but I'm not sure ...
    Thank you very much for you time !!
    bye :-))
    Fidalma

  • PreparedStatement and "in" clause

    I am trying to pass an "in" clause to a SQL statement as a bind variable, but keep getting an "invalid number" runtime error:
    The "where" clause of the SQL statement is:
    String wherestmnt = "where sh.header_id in ? ";
    I am using a PreparedStatement and am setting the bind variable as follows:
    pstmt.setString(1,"(34552)")
    If I change the "in" clause to "=" and do a set as pstmt.setString(1,"34552") it works fine.
    Any advice?
    null

    There is also another error. If you need to use the in clause the values must be within paranthesis,
    So if your query were like,
    select * from emp where empno in (?)
    then the bind would work. You can have as many ? as you want separated by commas and you can bind that many values..!

  • Difference b/w DATA TYPE and DATA OBJECT & differences b/w TYPE and LIKE

    hai
    can any one say the differences between Data type and Data Object.
    And also differences between TYPE and LIKE
    thanks
    Gani

    hi,
    _Data Types and Data Objects_
          Programs work with local program data – that is, with byte sequences in the working memory. Byte sequences that belong together are called fields and are characterized by a length, an identity (name), and – as a further attribute – by a data type. All programming languages have a concept that describes how the contents of a field are interpreted according to the data type.
          In the ABAP type concept, fields are called data objects. Each data object is thus an instance of an abstract data type. There are separate name spaces for data objects and data types. This means that a name can be the name of a data object as well as the name of a data type simultaneously.
    Data Types
       As well as occurring as attributes of a data object, data types can also be defined independently. You can then use them later on in conjunction with a data object. The definition of a user-defined data type is based on a set of predefined elementary data types. You can define data types either locally in the declaration part of a program using the TYPESstatement) or globally in the ABAP Dictionary. You can use your own data types to declare data objects or to check the types of parameters in generic operations.
         All programming languages distinguish between various types of data with various uses, such as ….. type data for storing or displaying values and numerical data for calculations. The attributes in question are described using data types. You can define, for example, how data is stored in the repository, and how the ABAP statements work with the data.
    Data types can be divided into elementary, reference, and complex types.
    a. Elementary Types
    These are data types of fixed or variable length that are not made up of other types.
    The difference between variable length data types and fixed length data types is that the length and the memory space required by data objects of variable length data types can change dynamically during runtime, and that these data types cannot be defined irreversibly while the data object is being declared.
    Predefined and User-Defined Elementary Data Types
    You can also define your own elementary data types in ABAP using the TYPES statement. You base these on the predefined data types. This determines all of the technical attributes of the new data type. For example, you could define a data type P_2 with two decimal places, based on the predefined data type P. You could then use this new type in your data declarations.
    b.  Reference Types
    Reference types are deep data types that describe reference variables, that is, data objects that contain references. A reference variable can be defined as a component of a complex data object such as a structure or internal table as well as a single field.
    c. Complex Data Types
    Complex data types are made up of other data types. A distinction is made here between structured types and table types.
    Data Objects
          Data objects are the physical units with which ABAP statements work at runtime. The contents of a data object occupy memory space in the program. ABAP statements access these contents by addressing the name of the data object and interpret them according to the data type.. For example, statements can write the contents of data objects in lists or in the database, they can pass them to and receive them from routines, they can change them by assigning new values, and they can compare them in logical expressions.
           Each ABAP data object has a set of technical attributes, which are fully defined at all times when an ABAP program is running (field length, number of decimal places, and data type). You declare data objects either statically in the declaration part of an ABAP program (the most important statement for this is DATA), or dynamically at runtime (for example, when you call procedures). As well as fields in the memory area of the program, the program also treats literals like data objects.
            A data object is a part of the repository whose content can be addressed and interpreted by the program. All data objects must be declared in the ABAP program and are not persistent, meaning that they only exist while the program is being executed. Before you can process persistent data (such as data from a database table or from a sequential file), you must read it into data objects first. Conversely, if you want to retain the contents of a data object beyond the end of the program, you must save it in a persistent form.
    Declaring Data Objects
          Apart from the interface parameters of procedures, you declare all of the data objects in an ABAP program or procedure in its declaration part. These declarative statements establish the data type of the object, along with any missing technical attributes. This takes place before the program is actually executed. The technical attributes can then be queried while the program is running.
         The interface parameters of procedures are generated as local data objects, but only when the procedure is actually called. You can define the technical attributes of the interface parameters in the procedure itself. If you do not, they adopt the attributes of the parameters from which they receive their values.
    ABAP contains the following kinds of data objects:
    a.  Literals
    Literals are not created by declarative statements. Instead, they exist in the program source code. Like all data objects, they have fixed technical attributes (field length, number of decimal places, data type), but no name. They are therefore referred to as unnamed data objects.
    b.  Named Data Objects
    Data objects that have a name that you can use to address the ABAP program are known as named objects. These can be objects of various types, including text symbols, variables and constants.
    Text symbols are pointers to texts in the text pool of the ABAP program. When the program starts, the corresponding data objects are generated from the texts stored in the text pool. They can be addressed using the name of the text symbol.
    Variables are data objects whose contents can be changed using ABAP statements. You declare variables using the DATA, CLASS-DATA, STATICS, PARAMETERS, SELECT-OPTIONS, and RANGESstatements.
    Constants are data objects whose contents cannot be changed. You declare constants using the CONSTANTSstatement.
    c.  Anonymous Data  Objects
    Data objects that cannot be addressed using a name are known as anonymous data objects. They are created using the CREATE DATAstatement and can be addressed using reference variables.
    d.  System-Defined Data Objects
    System-defined data objects do not have to be declared explicitly - they are always available at runtime.
    e.  Interface Work Areas
    Interface work areas are special variables that serve as interfaces between programs, screens, and logical databases. You declare interface work areas using the TABLES and NODESstatements.
    What is the difference between Type and Like?
    Answer1:
    TYPE, you assign datatype directly to the data object while declaring.
    LIKE,you assign the datatype of another object to the declaring data object. The datatype is referenced indirectly.
    Answer2:
    Type is a keyword used to refer to a data type whereas Like is a keyword used to copy the existing properties of already existing data object.
    Answer3:
    type refers the existing data type
    like refers the existing data object
    reward if useful
    thanks and regards
    suma sailaja pvn

  • What's the difference between "PreparedStatement" and "Statement"?

    What's the difference between "PreparedStatement" and "Statement"?
    Which is better??????

    Read the docs for the two classes. The differences are apparent there.
    Which one is better depends on your needs. I think that constructing and executing a PreparedStatement can be a bit less performant than just a Statement, if you're only executing the query one time. But I don't think that difference will normally be noticable in the context of a given application.
    Additionally, if you have to pass any dates or strings to the query, you'll want PreparedStatement's parameters, rather than trying to format and escape things in the query string.

  • At bottom of my screen where all my icons are I now have a picture of a key and like sound waves and a x and I cannot log on to a lot of my programs and don't k

    At bottom of my screen where desktop Icons are I have a picture of a key and like soundwaves and a red circle with an x in it. When this comes on I can't open a lot of my programs. I am a real novice and am not sure what to do.

    Please provide a screenshot of that "key".
    https://support.mozilla.org/en-US/kb/how-do-i-create-screenshot-my-problem
    It is best to use a compressed image type like PNG or JPG to save the screenshot and make sure that you do not exceed a maximum file size of 1 MB.
    Then use the '''Browse ....''' button below the '''''Post a Reply''''' text box to upload the screenshot.

  • Hi I wonder if I live in Bangkok and like to have my own website who should I use for hosting so many of them and how do I know which one is a good one thank you

    Hi I wonder if I live in Bangkok and like to have my own website whshah old I use as hosting website? so many of them and how do I know which one is a good one thank you

    It doesn't really matter which country your hosting service is located in so long as they offer 24/7 tech support in your chosen language. Telephone support is usually free of charge to you.
    Some info about the essential features to look for...
    http://www.iwebformusicians.com/iWeb/Website-Hosting.html
    "I may receive some form of compensation, financial or otherwise, from my recommendation or link."

  • Why Firefox 25.0 does not show Google ads and Facebook comments and likes. All other browsers do.

    I've just upgraded to FireFox 25.0 and I have issues viewing Google ads and Facebook comments and likes on my website (wellfitstyle.com). All other browsers show Google adds in the right sidebar and Facebook comments and likes under each post. Great number of people in Eastern Europe (where I am) use FireFox and I would like to know how this issue can be fixed.
    Tnx.

    Hi there,
    Starting in Firefox 23, if a secure page includes certain types of insecure content, Firefox blocks the insecure content and a shield icon will appear in the address bar. See this article for more information about the new mixed content blocker: [[How does content that isn't secure affect my safety?]]
    To temporarily allow the mixed content to be displayed:
    *Click the '''shield icon''' [[Image:Mixed Content Shield]] in the address bar and choose '''Disable Protection on This Page''' from the dropdown menu.
    [[Image:Fx23MixedContentBlocker]]
    To allow insecure content to be displayed in all secure pages, enter '''about:config''' in the address bar and double-click on this preference, to toggle it from true to false:
    '''security.mixed_content.block_active_content'''
    You can also use this add-on instead, to toggle the preference:
    *[https://addons.mozilla.org/firefox/addon/toggle-mixed-active-content/ Toggle Mixed active content] add-on
    You may want to do this only for the current session, then reset the preference back to "true" and check back with the site to see whether it's been fixed, since this is a global setting that exposes you on all sites, not just the one you care about.

  • PreparedStatement and bind variable

    We are experiencing some werid performance break downs where database server looks healthy and our java applications are down to their knees.
    I was wondering if someone could help me clarify the comparison between PreparedStatement and bind variable. When I execute a PreparedStatement in java through the JDBC thin driver, would the database consider it a dynamic SQL or is it a SQL using bind variable? If this same statement is executed 100000 times, is it parsed 100000 times? We are using JDK131. How does it work?
    Is there any memory leak in PreparedStatement implementation in JDBC thin driver? Is there any known symptom to this problem? What is the recommended solution?
    Thank you very much!

    If PreparedStatement is parsed and cached, why is there setting to set implicit statement caching and explicit statement caching? Our DBA insists that it is parsed every single time. How would I find out for sure?
    The SQLs have not been changed. This sudden performance degradation started when a new client went live and we experienced higher than usual volumn. We are connecting using JDBC thin client from weblogic server to Oracle 8.1.7. It's been happening everyday since the client went live and the only way to get the performance back is to shutdown and restart the database server.
    I tried to search JDBC related issues. The only complain that I've found so far is that there may be some potential memory leak for a PreparedStatement. However, I have not found anything from Oracle's website that concurs to that.
    What is my best bet?

  • PreparedStatement and batchExecute

    Hi,
    I am trying to use PreparedStatement and batchExecution for inserting a few rows into database. I am using JTurbo driver.
    But it only inserts the last set of values. For Example
    Class.forName( "com.ashna.jturbo.driver.Driver" );
    Connection con = DriverManager.getConnection( "jdbc:JTurbo://server","username","password" );
    PreparedStatement pstm = con.prepareStatement( "INSERT INTO Test( ids, age, wt ) VALUES(?,?,?)" );
    int ids[] = {1000,1001,1002,1003};
    String[] age = { "12","13","14","15" };
    String[] wt = { "45","46","47","48" };
    for( int i=0 ; i<ids.length ; i++ )
    pstm.setInt( 1, ids[i] );     
    pstm.setString( 2, age[i] );
    pstm.setString( 3, wt[i] );     
    pstm.addBatch();
    int[] rows = pstm.executeBatch();
    pstm.clearBatch();
    con.close();
    In database, it shows
    1003, 15, 48
    1003, 15, 48
    1003, 15, 48
    1003, 15, 48
    Pls..pls..help me with this...i'm having a hard time figuring out this problem.. :(
    Thanks a lot...

    Maybe you just wrote this short-hand but if not try this:
    pstm.setInt( 1, ids[i] );
    pstm.setString( 2, age[i] );
    pstm.setString( 3, wt[i] );
    //...........

  • When i was scrolling through my camera role today before i updated and like 100   pictures turned into a picture thats white then says PNG. Cant see the picture. What should i do?

    when i was scrolling through my camera role today before i updated and like 100 + pictures turned into a picture thats white then says PNG. Cant see the picture. What should i do?

    I seem to have fixed it by putting <div  class="clearfloat"></div> after the navigation bar?

  • HT3743 I purchased an iphone 3g that was to be open to any carrier, I went to restore it to my itunes account and get a 1015 error, can this be fixed.  I am new to the iphone and like the product but cannot buy new.  Please help. THANKS

    I purchased an iphone 3g that was to be open to any carrier, I went to restore it to my itunes account and get a 1015 error, can this be fixed.  I am new to the iphone and like the product but cannot buy new.  Please help. THANKS

    You got ripped off. You bought a hacked/jailbroken phone. That's what error 1015 means. Return it and get your money back if possible and buy a phone from a legitimate source.
    Discussing jailbroken / hacked phones is forbidden by the terms of service. Jailbreaking / hacking voids any warranty and forfeits your right to support here or from Apple. You can not get help here.

  • Database Procedure Calling by Using PreparedStatement and CallableStatement

    Hi
    We can execute Database Stored Procedure by using PreparedStatement and CallableStatement as well.Then what is the significance of having CallableStatement.
    Please let me know the difference between these two Statement objects particularly in Stored Procedures Execution.
    Thanks in advance
    Basha007

    A callable statement excecutes a stored procedure that's stored and run on the database server.
    A prepared statement doesn't require a database stored procedure. It's parsed and cached by the JDBC driver, and allows you to specify parameters and bind values to them at runtime. Those are usually used in loop constructs where you want to repeatedly execute the same SQL with different values.
    Not all RDBMS support stored procedures (e.g., MySQL), but every driver I've used allows PreparedStatements. - MOD

  • To Joe Schell - jschell... - PreparedStatement and executeBatch()

    Hi,
    Thanks for the reply to the PreparedStatement and executeBatch() query. Is there any workaround for it other than using the Statement object?
    thanks,
    Nish

    Could be.
    But since I have no idea about what you are talking about, I can't really comment.
    I respond to between 10-30 threads a day and read more than that. Consequently I need a context to understand questions.
    If I have previously (recently) responded to a previous thread then if you post a response to it I will generally see it in less than a day. If is an older thread you might want to start a new thread. But if you do then add a link or put enough content so I can follow it.

Maybe you are looking for