Feenix
Feenix

Reputation: 11

How do you query database using a variable? Dynamic SQL...?

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.

Upvotes: 0

Views: 172

Answers (2)

Dibakar Paul
Dibakar Paul

Reputation: 166

Use PrepareStatement like,

String word = "Apples";
PreparedStatement st = conn.prepareStatement("SELECT * FROM table WHERE name = ?");
st.setString(1, word);
ResultSet rs = st.executeQuery();

Upvotes: 3

Sanghita
Sanghita

Reputation: 1317

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

Upvotes: 0

Related Questions