Skip to content
Advertisement

Retrieve database in java using JTextField to search

So, i would like to retrieve database information where a user will search certain columns using text fields, like this:

column1 find userinput, column2 find userinput, column3 find userinput,

The problem im having is the sql statement:

String sql = "select * from table where column = '" + textfield1.getText() + "'";

If textfield1 is empty, it will only retrieve entries that contain nothing.

What im trying to retrieve will have 6 text field, meaning 6 columns in the database. Using java i would need alot of if statements.

Is there any other way to shorten this?

EDIT — MORE INFO —

The if statements will start from:

if (!(t1.getText().equals("")) && !(t2.getText().equals("")) && !(t3.getText().equals(""))
&& !(t4.getText().equals("")) && !(t5.getText().equals("")) && (t6.getText().equals("")))

all the way down to

if (t1.getText().equals("") && t2.getText().equals("") && t3.getText().equals("")
&& t4.getText().equals("") && t5.getText().equals("") && t6.getText().equals("")

covering all possible combinations of the 6 input fields, the point of all these statements is to ignore empty text fields but provide the corresponding sql statement.

I don’t know how to calculate the possible combinations other than writing them all down(i started, there was too many).

Advertisement

Answer

I didn’t really understand why those ifs, you should elaborate more your question but i will try to help as i can.

Well, if you want to retrieve everything from the database you could use LIKE:

String sql = "select * from table where column like '%" + textfield1.getText() + "%'";

This way you’ll get everything with the containing text, it means, if the field is empty it will bring all results, i guess this is the best way to do, to avoid unnecessa if clauses.

Another thing, to check for empty fields you should use:

t1.getText().trim().isEmpty()

BUT if you let they write white spaces the LIKE won’t help you then you need to .trim() all your texts then your white spaces will be ignored.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement