Share this page 

SELECT data from a tableTag(s): JDBC


Note:the MyConnection class was used to connect to the DB

With a Prepared Statement (only 1 row)
String id = cust_id.getText();
try {
  PreparedStatement prepstmt;
  boolean found = false;
  prepstmt = theConn.prepareStatement
    ("select custName, CustAddr from tCust where custId = ?");
  prepstmt.setString(1, id); 
      
  ResultSet rs;
  rs = prepstmt.executeQuery();
      
  found = rs.next();
  if (found)
      System.out.println(rs.getString(1));
  else
      System.out.println("Customer " + id + " not found!");
   prepstmt.close();
   }
catch (Exception e) {
   e.printStackTrace();
}
With a Statement (many rows)
String name = cust_name.getText();
try {
  Statement stmt;
  String sql;

  sql =  "select custName from tCust where custName = "
     += "'" + name + "'";
  stmt = theConn.createStatement();
      
  ResultSet rs;
  rs = stmt.executeQuery();
       
  while (rs.next()) {
    System.out.println(rs.getString("custName"));
    }
  rs.close();
  stmt.close();
  }
catch (Exception e) {
  e.printStackTrace();
}

You need to be aware to the snippet above contains a SQL Injection vulnerability. String concatentation of this form can only be used if you first validate the fields to include only alphanumeric characters. Even, then it is generally considered bad practice when prepared statements solve this problem more cleanly. This is especially when you in a Web application environnement.

Thanks to Lawrence Angrave for the warning.