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 =;
  if (found)
      System.out.println("Customer " + id + " not found!");
catch (Exception e) {
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 ( {
catch (Exception e) {

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.

blog comments powered by Disqus