0

I'm wondering how to search a database table using a given variable or an array in the SQL query. I'm currently using Java and PostgreSQL and I want to do something like:

String word = "Apples";
SELECT * FROM table WHERE name = word;

or

token[0] = "Apples";
SELECT * FROM table WHERE name = token[0};

Does anyone know the correct way to do this?

My eventual goal is simply to check the database to see if a word that a user has input is stored in the database and if it is then do something with that word.

1

2 Answers 2

3

Use PrepareStatement like,

String word = "Apples";
PreparedStatement st = conn.prepareStatement("SELECT * FROM table WHERE name = ?");
st.setString(1, word);
ResultSet rs = st.executeQuery();
Sign up to request clarification or add additional context in comments.

3 Comments

When I try this I get the error message: error: cannot find symbol PreparedStatement st = conn.prepareStatement("SELECT * FROM table WHERE name = ?");
Is it compile time exception or runtime? Did you import, import java.sql.PreparedStatement;
0

If you want to fetch data in java end, do something like:

Connection con = DriverManager.getConnection
  ("jdbc:derby://localhost:1527/testDb","name","pass");
  PreparedStatement updateemp = con.prepareStatement
  ("insert into emp values(?,?,?)");
  updateemp.setInt(1,23);
  updateemp.setString(2,"Roshan");
  updateemp.setString(3, "CEO");
  updateemp.executeUpdate();
  Statement stmt = con.createStatement();
  String query = "select * from emp";
  ResultSet rs =  stmt.executeQuery(query);

See full details : Here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.