Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Fetch one record only and not a list of records

Status
Not open for further replies.

oaklanders

Technical User
Dec 9, 2007
38
I have a class that fetches a record but dont think I need to use List object because I am fetching one record and not an array of records.

Code:
public List getRecords(){
        ResultSet rs = null;
        Statement stmt = null;
        Connection connection = null;
 
        List rows = new ArrayList();
        
        try
        {
            Class.forName("org.gjt.mm.mysql.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost/dbase?user=myname&password=thepassword");
            stmt = connection.createStatement();
            rs = stmt.executeQuery("SELECT * from user where userid = 10");  
            
            while(rs.next()){
            RowBean row = new RowBean();
            row.setFirstname(rs.getString("firstname"));
            row.setLastname( rs.getString("lastname"));
            rows.add(row); 
            .....

Would this be correct to just return a RowBean object and if so am I doing it correctly?
Code:
public RowBean getRecord(){ 
        ResultSet rs = null; 
        Statement stmt = null; 
        Connection connection = null; 
 
 
        //List rows = new ArrayList(); 
        RowBean row = new RowBean();
 
        try 
        { 
            Class.forName("org.gjt.mm.mysql.Driver"); 
            connection = DriverManager.getConnection("jdbc:mysql:// 
localhost/dbase?user=myname&password=thepassword"); 
            stmt = connection.createStatement(); 
            rs = stmt.executeQuery("SELECT * from user where userid = 
10"); 
 
 
            while(rs.next()){ 
           
            row.setFirstname(rs.getString("firstname")); 
            row.setLastname( rs.getString("lastname")); 
            //rows.add(row); 
            }
            ..... 
            //last part of method I would return the RowBean object:
            return row;
}
 
That will return the last record. If there will be only one, there's no need of a while loop, you can just call next() and retrieve the values.

If you want the last, you can use the afterLast() method to avoid iterations.

Cheers,
Dian
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top