Searching with only some criteria

I have a database table with six columns, all of which are nullable.
The user has a search screen with one input for each column,
and I'd like to return all matching values. I'm using a prepared
statement that looks something like:
select *
from MY_TABLE
where COLUMN1 like ?
  and COLUMN2 like ?
  ...My problem arises when a user doesn't enter values for all six
search conditions. I can't put in "" or null for the parameters, because
then it will explicitly search for those values. I can't not call setString()
on the column numbers I'm not interested in.
Right now I'm stuck with:
private final static String SEARCH =
  "select * from TABLE where";
public void myMethod() {
  final StringBuffer buffer = new Stringbuffer(SEARCH);
  final String name = httpRequest.getParameter("name").trim();
  if (!name.equals("")) {
    buffer.append("NAME like '");
    buffer.append(name);
    buffer.append("'");
  // magic 'and' insertion here if required
  final String id = httpRequest.getParameter("id").trim();
  if (!id.equals("")) {
    buffer.append("ID like '");
    buffer.append(id);
    buffer.append("'");
}That gets really ugly over multiple items. Is there no better way?
My coworkers insist this is my only choice, but I don't believe them.
Thanks!

I wound up writing a helper class to handle the situation. Right now
it only works with Strings.
* <p>This class wraps any search query with a dynamic 'where' clause.</p>
* <p>Create a ConditionalQuery instance with the static clauses which
* appear before ("select FOO from BAR") and after ("order by BAZ") your
* dynamic 'where' clause.  For each search parameter you may be using,
* invoke addCondition() with the column name and the search value.  If
* the value is "", it will be ignored.  Otherwise, the value will be
* added to the search criteria.</p>
* <p>Once you have passed in all criteria, invoke getStatement() to
* get a PreparedStatement you can query.  The values for the query
* parameters will already be added to the PreparedStatement.</p>
* <p>Sample usage:</p>
* <code><pre>
private static final String baseQuery = "select MAIL from LD_USERS_DUMP";
private static final String orderClause = "order by MAIL";
public void getEmailAddress(final String lastName, final String comitID) {
    final ConditionalQuery query =
        new ConditionalQuery(baseQuery, orderClause);
    query.addCondition("SN", lastName);
    query.addCondition("LDAP_UID", comitID);
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    try {
        connection = DatabaseFactory.getConnection("Oracle");
        preparedStatement = query.getStatement(connection);
        resultSet = preparedStatement.executeQuery();
    } catch (final SQLException se) {
        LOGGER.error("Database error.", se);
    } finally {
        DatabaseUtilities.close(resultSet);
        DatabaseUtilities.close(preparedStatement);
        DatabaseUtilities.close(connection);
</pre></code>
* <p>This class is final because it is not designed to be extended.</p>
* <p>This class is <strong>not</strong> thread-safe.</p>
* @author Eric Stein (xbbjgns)
public final class ConditionalQuery {
     * Contains the contents of this query up to the end of the
     * 'where' clause.
    private final StringBuffer query = new StringBuffer();
    /** Clause which goes after the 'where' clause.  May not be null.*/
    private final String postConditionClause;
     * String list of condition values, in the order they were added. */
    private final List values = new ArrayList();
     * True if this query has one or more conditions, false if there
     * are zero conditions.
    private boolean hasConditions = true;
     * Constructor.
     * @param baseQuery clause to put before the 'where' clause in
     * the query.  May not be null.
     * @throws NullPointerException if the baseQuery parameter is null.
    public ConditionalQuery(final String baseQuery)
    throws NullPointerException {
        this(baseQuery, "");
     * Constructor.
     * @param baseQuery clause to put before the 'where' clause in
     * the query.  May not be null.
     * @param postConditionClause clause to put after the 'where' clause
     * in the query.  May not be null.
     * @throws NullPointerException if either parameter is null.
    public ConditionalQuery(final String baseQuery,
            final String postConditionClause)
    throws NullPointerException {
        ValidationUtilities.checkNotNull(baseQuery, "baseQuery");
        ValidationUtilities.checkNotNull(postConditionClause,
            "postConditionClause");
        this.query.append(baseQuery.trim());
        this.query.append(" ");
        this.postConditionClause = postConditionClause;
     * Adds a condition to this query.  If the value to search for is
     * "", this method will do nothing.  If there is a search value,
     * the column and value get added to the prepared statement.  By
     * default, conditions are <strong>not</strong> case-sensitive.
     * @param columnName the name of the column a condition is being
     * added for.  May not be null.
     * @param value the value for the condition being added to the query.
     * May not be null.
     * @throws NullPointerException if either parameter is null
    public void addCondition(final String columnName, final String value)
    throws NullPointerException {
        this.addCondition(columnName, value, false);
     * Adds a condition to this query.  If the value to search for is
     * "", this method will do nothing.  If there is a search value,
     * the column and value get added to the prepared statement.
     * @param columnName the name of the column a condition is being
     * added for.  May not be null.
     * @param value the value for the condition being added to the query.
     * May not be null.
     * @param caseSensitive true for string comparisons to be
     * case-sensitive, false for them to ignore case.
     * @throws NullPointerException if the columnName or value parameters
     * are null.
    public void addCondition(final String columnName, final String value,
            boolean caseSensitive)
    throws NullPointerException {
        ValidationUtilities.checkNotNull(columnName, "columnName");
        ValidationUtilities.checkNotNull(value, "value");
        final String trimmedValue = value.trim();
        if (trimmedValue.equals("")) {
            return;
        if (this.hasConditions) {
            this.query.append("and ");
        } else {
            this.query.append("where ");
            this.hasConditions = true;
        if (caseSensitive) {
            this.query.append(columnName); 
        } else {
            this.query.append("upper(");
            this.query.append(columnName);
            this.query.append(") ");
        this.query.append(" like ");
        if (caseSensitive) {
            this.query.append("? ");
        } else {
            this.query.append("upper(?) ");
        this.values.add(value);
     * Creates a PreparedStatement from this query.  The parameters
     * for the PreparedStatement are already set.
     * query.  Will never return null.
     * @param connection the connection a prepared statement is being
     * created for.  May not be null.
     * @return a PreparedStatement whose values are set.  Will never return
     * null.
     * @throws NullPointerException if the connection parameter is null.
     * @throws SQLException if an error occurs while preparing the
     * statement.
    public PreparedStatement getStatement(final Connection connection)
    throws NullPointerException, SQLException {
        ValidationUtilities.checkNotNull(connection, "connection");
        final PreparedStatement statement =
            connection.prepareStatement(this.getQuery());
        for (int i = 0; i < this.values.size(); i++) {
            statement.setString(i + 1, (String) this.values.get(i));
        return statement;
     * Returns true if this query has at least one search condition,
     * or false if it has no conditions.
     * @return true if this query has at least one search condition,
     * or false if it has no conditions.
    public boolean hasConditions() {
        return this.hasConditions;
     * Returns a string representation of this query.
     * @return a string representation of this query.  Will never
     * return null.
    public String getQuery() {
        return this.query.toString() + this.postConditionClause;
}

Similar Messages

  • Create smart album with ONLY some faces

    Hi. I need some help here. I created a smart album and I want it to have photos where only my girlfriend and I appear. I put two conditions: Face-is-my_name, and Face-is-mygirlfriend'sname. The problem is that it creates the album but it also contains photos where we and someone else appears, not only the two of us. Is there any way I can get it done?
    Thanks for your posts.

    Yes, I said to meet ALL conditions, and my smart album is in fact just like you said, with photos that have both of us but also other people.
    But I get it, the only way to exclude other people is specifically by name. I just wanted to know if there was another "more automatic" way. Thanks a lot LarryHN.

  • Really bad distortion with only some files and ga

    Hello,
    I recently bought an audigy 2 value 7.. Works like a charm with winamp, media player etc..
    however, whenever I try to play certain files with VLC media player or even some games (example, only the opening of Rise of nations) i get crazy distortion.
    I have a P4 2.3 with 384 Ram. I have reinstalled the drivers, and still no luck. Please help so I can watch the movies that are being affected.
    Ryan

    can someone please help me!!!!!!!!!!!

  • PSD comp field issue with only some elements

    I have a comp created from a layered psd file, I have animated it and most elements are fine, except this one, have a look at the frame I exported. A field issue but why only with one of the elements? When it is un-rendered it draws fine, rendered though and I get this, this layer continues on for longer than the two minute limit as well, so I had to duplicate/copy the layer, the copied version is fine...
    Also it is intermittent.
    http://www.digital-image.com.au/videos/fcp/

    hi preethi ,
    just check this code .
    data : quant like ekpo-menge,       " ur data type
              v_quant(13) type c.                     " --->proposed
              quant = 0.                                 " made initial.
              v_quant = quant.
    write:/ quant.                         
    if quant is initial.
    write:/ 'hi'.                            "gets triggered cause some value is there
    endif.
    if v_quant is initial.
    write:/ 'hi'.                           "even though value is there dosent get triggered
    endif.
                           "cause its character.
    if u can make the screen field as character then u can have solution in my opinion .
    just check if this alternate can help ur code ..
    regards,
    vijay.

  • Kopete - webcam will connect with only some contacts

    My PC is behind a NAT router, but I've already opened the port that MSN uses to connect the webcam, so I can see others webcams and some of my contacts also can see mine. The problem is that not all of my contacts can see my webcam.
    I thought it could be a problem with the other person's router, but I was talking to a friend with whom I can't connect my webcam and she can see others webcam. It seems not to be a problem with different versions, because some contacts have MSN Messenger 8 and it works, with others who also have MSN Messenger 8, it won't work.
    I'm completelly lost.

    Hello andre,
    but I've already opened the port that MSN uses to connect the webcam,
    could you please tell me the port? I have also the problem that my router is blocking this port, but I don't know which one it is.
    It seems that there are often some problems with MSN and p2p connections like webcam, file transfer etc. I have the same problem: with some contacts it works perfectly, with others it doesn't.
    maschino

  • Use grouped checkboxes with only some secured with password?

    Hi,
    I have a set of 4 checkboxes on my form that I have set as a radio group so that only 1 checkbox may be checked at once.  But I'd like to use Mr. George Johnson's JavaScript code on only 2 of the checkboxes so that those 2 cannot be checked unless the person has the password while the other 2 can be freely chosen without a password.  Is there a way to do this either within the code or just with the form properties?
    Thanks,
    Misery9980

    I have a fwe more questions and a comment. When exactly are the fields going to be locked? If they will be locked and then sent to a user to complete, and one of the check boxes that gets locked is selected, do you want the user to be able to select one of the ones that are unlocked, which will cause the locked check box to be deselected? In other words, the user will be able to change one of the locked fields by selecting one of the unlocked ones. Is that OK?
    The other problem with this approach is if a user has JavaScript disabled (or are using a non-JavaScript-capable viewer), they will be able to select more than one of the unlocked check boxes at a time. Because the behavior of the group of check boxes will be controlled through JavaScript, overriding the normal behavior, this could lead to an inconsistent state for the form. Is that acceptable?

  • Ipod touch working with only some earbud brands?

    All of a sudden, the Sennheiser earbuds I've been using when I run for about a year started making tracks sound..."robotic" or with an exaggerated echo. I tried my Apple earbuds and it worked fine as well as a pair of Sony earbuds and no problem. I thought it was my Sennheiser's that were faulty and grudgingly purchased a pair of  yurbuds to replace them. Same symptoms as before with the Yurbuds...Robotic and/or echo. Could this be the new OS? Could Apple have made it so that you could only use apple earbuds? They would not be so relentless would they?

    I just got a beats audio headset and it works absolutely great with my iPod touch. I suggest for you to buy one as well.

  • Remote control issue with only some users

    I'm having an issue that I can't seem to find any reference to anywhere.
    Our client has two servers. One is Server 2003 and is running AD, the other is 2008R2 and is running terminal services.
    When I create a new user in AD, if I set the option in AD to allow remote control, do not require permission and interact and I set these options before the first time the user logs into the terminal then I can remote control that user's session without
    a problem.
    However, if I leave the defaults in AD to allow remote control but require the user's permission and the user logs into the terminal the first time with permissions set like that then forever more I can never remote into that user's sessions. Changing the
    options in AD later to not require user's permission no longer helps. When I try to remote into that user's session the user does not get a pop-up requesting permission, rather I just get an Access Denied message. If I try to shadow via an elevated command
    prompt I get error 317. I haven't been able to find any differences in GP or the registry between users that I can shadow and those I can't. Some setting specific to each user is getting set on first login that can't seem to be undone by changing the settings
    in AD. Where might I find this?
    Thanks!

    Hi,
    Thank you for posting in Windows Server Forum.
    Please check that you have added user under “Remote Desktop User” local group. In addition they are
    added under GPO setting “Allow logon through Remote Desktop Services” and
    not added under “Deny logon through Remote Desktop Services”.
    You can check the setting under below mention path.
    GPO_name\Computer Configuration\Windows Settings\Security Settings\Local Policies\User Rights Assignment
    More information:
    Allow log on through Remote Desktop Services
    http://technet.microsoft.com/en-us/library/dn221985.aspx
    In addition please check that you are not limiting in number of users who can connect simultaneously and also verify Remote Desktop Services Logon rights. Please check beneath article for additional details.
    Remote Desktop disconnected or can’t connect to remote computer or to Remote Desktop server (Terminal Server) that is running Windows Server 2008 R2
    http://support.microsoft.com/kb/2477176
    Hope it helps!
    Thanks, 
    Dharmesh

  • Only some music syncing?

    Hi, I’ve recently had a problem syncing my iPad with music I already have on iTunes (some purchased from ITunes and some not, built up over the years). I want to have all my music (the ones ticked in iTunes) on the iPad but it just doesn’t seem to be transferring them across, with only some of them now appearing on my iPad?
    Not sure why? This has only happened recently, not sure whether this is as a result of updating to IOS 8.02 on the iPad?
    I've already tried deleting all music from the iPad and reloading from my PC, but it still keeps happenening?
    Any thoughts.

    Try:
    - Reset the iOS device. Nothing will be lost
    Reset iOS device: Hold down the On/Off button and the Home button at the same time for at
    least ten seconds, until the Apple logo appears.
    - Unsync all music and resync
    - Reset all settings
    Go to Settings > General > Reset and tap Reset All Settings.
    All your preferences and settings are reset. Information (such as contacts and calendars) and media (such as songs and videos) aren’t affected.
    - Restore from backup. See:       
    iOS: How to back up           
    - Restore to factory settings/new iOS device.

  • Why am I having trouble receiving text messages from only some people

    I have turned off my imessaging and only some of my contacts are having trouble sending messages to me when they have imessage turned on.  They receive a message that says Not Delivered.  Why am I having this issue with only some of my contacts? How can I fix this?

    Hi,
    I was quite specific about which .plist to delete as if you have no other issues it is pointless deleting the AIM or Subnet (Bonjour) or Yahoo ones as they will not effect the Jabber logins.
    Deleting the LLSharing list one only removes items from the Recent Lists in the File menu > Recent Items.
    The Status Messages one only deletes the Saved Status Messages you may have made for Buddy lists.
    Deleting com.apple.ichat.plist itself mostly messes up your Preferences and some menu choices.
    Try deleting com.apple.imagent.plist as this is involved with logging in the Accounts to the various servers.
    9:35 pm      Wednesday; January 8, 2014
      iMac 2.5Ghz 5i 2011 (Mavericks 10.9)
     G4/1GhzDual MDD (Leopard 10.5.8)
     MacBookPro 2Gb (Snow Leopard 10.6.8)
     Mac OS X (10.6.8),
     Couple of iPhones and an iPad

  • My iphone 3G has worked fine via bluetooth with my BMS 3 series (57 plate) until I updated to V.5.0.1 software and now only some but not all contacts are transferred - any ideas?

    My iphone 3G has worked fine via bluetooth with my BMS 3 series (57 plate) until I updated to V.5.0.1 software and now only some but not all contacts are transferred and available - any ideas?

    Rodger,
    Thank you for your gracious welcome . . .
    and thank you for your swift response . . .
    and thank you for your information (and encouragement!).
    Yes, I read that too, but searched in vain for the specifity of, say, your direction:
    "Go ahead and update to 8.0.2, as it contains the 8.0.1 update."
    So I shall!
    Again, many thanks.

  • I recently upgraded from an 80 to 160GB Classic but only some of the artwork in iTunes is synching. There was no problem with the old 80Gb classic. any suggestions?

    I recently upgraded from an 80 to 160GB Classic but only some of the artwork in iTunes is synching. There was no problem with the old 80Gb classic. any suggestions?

    here is an interesting thing: take the iphone and set lock screen to never. Now make an email with siri--be sure to activate her with call button. get to the body and get some text in there. then just stop talking. LOCK SCREEN APPEARS!!!!!! and of course you draft is gone.
    There does seem to be a work around for some--maybe all these issues. Don't use the call button--use the buttons on the phone.
    Siri seems to behave properly with scenerio above---sans call button. She does not go to lock.

  • Export with all objects and only some table data

    Hi,
    can we use exclude and include both at a time.Because I want export full schema but data required only some 5 table, Is it possible.
    please share expdp and impdp query.
    Regs,
    Brijesh

    Hello,
    can we use exclude and include both at a time.No, EXCLUDE and INCLUDE are mutually exclusive.
    I want export full schema but data required only some 5 table, Is it possible.You can make 2 separate Exports:
    - *1.* With the metadata only, by using the parameter below:
    CONTENT=METADATA_ONLY- *2.* With the Data of the 5 Tables.
    The _1st Export_ will let you have all the Objects of the Schema but you won't have any rows.
    For this _2nd Export_, you may use the INCLUDE parameter so as to select the 5 Tables for which you need Datas. As previously posted, the QUERY parameter let you apply a filter on the rows for each Tables. By that way you'll have only an extract of the content of the 5 Tables.
    NB: The use of a Parameter File is recommended so as to manage better all the Parameters you need, and avoid some troubles with some special characters.
    Hope this help.
    Best regards,
    Jean-Valentin
    Edited by: Lubiez Jean-Valentin on Apr 19, 2011 5:43 PM

  • Only some pages of my website made with Muse can't be edit in the Business Catalyst Admin Console... How access all my pages edit possibilities ?

    My website is made with Adobe Muse and published with Business Catalyst.
    Some pages can be edit on the Business Catalyst Console, but, unfortunately, some other pages can't.
    Why some pages and not others ?
    Thanks for yours answers.

    Hi,
    I have try the edit mode with Firefox and Chrome and no one doesn’t work.
    For the french pages, I must reload the page to have the blue blocks. And if I do that on an english one, it switches on the french one...
    Caroline Duhamel
    +33 (0)6 08 34 33 61
    Le 24 oct. 2014 à 09:40, rohit776 <[email protected]> a écrit :
    Only some pages of my website made with Muse can't be edit in the Business Catalyst Admin Console... How access all my pages edit possibilities ?
    created by rohit776 in Help with using Adobe Muse CC - View the full discussion
    Hi,
    I have just checked at my end and it seems everything is working fine and I am able to edit even the English version pages.
    Can you please try some other browser or in a different system to edit your site and check if you are able to do so.
    Regards,
    Rohit Nair
    Please note that the Adobe Forums do not accept email attachments. If you want to embed a screen image in your message please visit the thread in the forum to embed the image at https://forums.adobe.com/message/6862093#6862093
    Replies to this message go to everyone subscribed to this thread, not directly to the person who posted the message. To post a reply, either reply to this email or visit the message page:
    To unsubscribe from this thread, please visit the message page at . In the Actions box on the right, click the Stop Email Notifications link.
    Start a new discussion in Help with using Adobe Muse CC by email or at Adobe Community
    For more information about maintaining your forum email notifications please go to http://forums.adobe.com/thread/416458?tstart=0.

  • Q-10 Calandar not syncing with Outlook, only some of the appointments show up?

    Anyone know why when I sync my phone with my computer, only some of the appointments from outlook show up on my phone?  this just started happening about a week ago?  Did I turn something off?  any help would be appreciated.
    Tony 

    I do not know why but from what you said it started a week ago so I assume it was working before that.
    Can you remember installing any new apps or updates on your computer or phone around that time.

Maybe you are looking for

  • GR-GOODS RECEIPT

    HELLO FRIENDS, WHILE DOING A GR WITH RESPECT TO A PURCHASE ORDER THE STOCK ACCOUNT GETS DEBITED AND THE GR/IR ACCOUNT GETS CREDITED. NOW MY QUESTION IS THE AMOUNT WHICH SHOWS IN THE STOCK ACCOUNT ASWELLAS THE GR/IR ACCOUNT IS WHICH AMOUNT TAKEN FROM

  • Why can't I see the changes in my image when I move the sliders in LR's Develop Module

    When I use the quick develop tools in the LR 5.3 Library module, I see the changes in the selected image. When I switch to the Develop Module, when I move the sliders for the different tools, nothing happens to my image. When I go back to the Library

  • Styling dynamic text

    I have an empty text field that will be filled with some dynamic text depending on what random number is rolled. How can I make just one word in one of those sentences italicized? I don't see any obvious ways to do it. Any help would be appreciated,

  • G5 locks up when logging out and other concern

    This has become a problem over the past year. I know that it is an old single processor, first of the Power Macs, legacy machine and OS. I have gone through all various check system/disk evolutions with Apple and TechTool Utilities. Also, when I have

  • Function module which will capture system generated errors

    hi gurus,   What is the name of the function module which will capture system generated errors and will populate a internal table?