0

I have code to retrieve a database item and it displays that in a mobile application using J2ME. I also use JSP for this so that my mobile app can get information from this.

I want to know how I can retrieve multiple items??

JavaBean:

public String doQuery() throws ClassNotFoundException, SQLException {
     //register driver
    DriverManager.registerDriver(new com.mysql.jdbc.Driver());

     //establish connection
    Conn = DriverManager.getConnection ("jdbc:mysql://localhost:3306/a1electric?user=root&password=raam030");

     //Create a Statement object from the Connection
    Statement stmt = Conn.createStatement();

    String sql = "SELECT JobID FROM employee WHERE employeeID=" +this.jobID;
    ResultSet rs = stmt.executeQuery(sql);
    String rt = "";
    rs.next();
    rt =  rs.getString("JobID");
    Conn.close();
    return rt;
   }

JSP Page:

  <jsp:useBean id="bean0" scope="session" class="data.queryBean"/>
<jsp:setProperty name="bean0" property="jobID" param="jobID"/>
<%= bean0.doQuery() %>

I would like to retrieve all the job IDs for this employee ID and display it.

1 Answer 1

6

If there are multiple JobIDs for a given EmployeeID, then your result set has all those items and you should browse through the resultset:

String sql = "SELECT JobID FROM employee WHERE employeeID=" +this.jobID;
ResultSet rs = stmt.executeQuery(sql);
List<String> jobIds = new ArrayList<String>();
while (rs.next()) {
    jobIds.add(rs.getString("JobID"));
}

On a related note, you should

  1. try to use a connection pool (apache DBCP), instead of registering the driver and connecting to the DB everytime.
  2. use PreparedStatement to avoid potential SQL injection attacks:

    PreparedStatement stmt = con.prepareStatement(
        "SELECT JobID FROM employee WHERE employeeID= ?");
    stmt.setInt(1, this.jobID);
    ResultSet rs = stmt.executeQuery();
    
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for that.. This is for my college project so I am not concerned about the security part at this time.

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.