aspose file tools
The moose likes JDBC and Relational Databases and the fly likes Prepared Statement with wild card Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "Prepared Statement with wild card " Watch "Prepared Statement with wild card " New topic
Author

Prepared Statement with wild card

Shriyan San
Greenhorn

Joined: Mar 15, 2005
Posts: 9
I have a sql query
stmt = conn.prepareStatement("SELECT * FROM TABLE WHERE name LIKE ?");

in my prepared statement i have
stmt.setString(1,"someval");

how do i use LIKE ?% wild card with prepared statement. some reason it's not accepting the % in statement. Help me.
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 31571
    
185

[ignore this post - I misread the question]

Shriyan,
You can't use a wildcard that way. A ? can only substitute for a string literal. So you could do "... where name like ( ?, ?, ? )" if you knew there were going to be three strings.

Without this knowledge, you have to build up the SQL at runtime.
[ June 30, 2005: Message edited by: Jeanne Boyarsky ]

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 62118
    
  68

I see no % anywhere in your code

When used, the wildcards must be part of the parameter string, not the SQL statement.
[ June 29, 2005: Message edited by: Bear Bibeault ]

[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Shriyan San
Greenhorn

Joined: Mar 15, 2005
Posts: 9
I tried this way it worked

stmt = conn.prepareStatement("SELECT * FROM TABLE WHERE name LIKE ?");

String val="someval";
stmt.setString(1,val+"%" );

Thanks a lot.
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

Glad you got there Isn't it nice when you get the last step on your own rather than being handed the answer
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Prepared Statement with wild card