Question:
Java and sql. How to search?
2008-06-12 04:50:31 UTC
I am using java to add, update and delete from a access database. Here is my code to add a entry.
sqlQuery = "insert into Customers values(" +
txtCustNo.getText() + ", '"+
txtName.getText() + "', '" +
txtPhone.getText() + "', #" +
txtBDay.getText() + "#)";
n = stmt.executeUpdate(sqlQuery);

But now I need to search the database and I am having lots of trouble. I really don't know how ot start. Here is what I have

String sqlQuery = "select * " + "from Customers where Name Like '" + namemem + "';";
System.out.println(sqlQuery);
n = stmt.executeUpdate(sqlQuery);

I am searching for a name so I want to have the user only put in a few letters of the name and the results pop up in a JOptionWindow.
any thoughts?
Three answers:
Mike S
2008-06-12 04:59:41 UTC
almost got it. you need to use '%' as wildchar character for like. Without wildchar it behaves as '='

String sqlQuery = "select * " + "from Customers where Name Like '" + namemem + "%';";



Like is case sensitive. If you want to search for 'namemem' anywhere in a field use "%"+namemem+"%...
2008-06-12 12:33:03 UTC
There is no need to write this much of hectic code

use this on



String name ="name to search" ;



String query = " select * from table where name like %?%";

PreparedStatement ps = con.prepareStatement( query ) ;



ps.setString( 1 , name ) ;



ResultSet rst = ps.executeQuery();



while( rst.next( ) )

{

System.out.println( rst.getString (1 ) ) ;

System.out.println( rst.getString (2 ) ) ;

System.out.println( rst.getString (3 ) ) ;



}



here con is connection object
Schmee007
2008-06-12 11:54:41 UTC
If you want the name to pop up as you are typing it, you need to use AJAX.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...