954,518 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Fetch one record instead of List of records

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.

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?

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;
}
chicago1985
Light Poster
36 posts since Nov 2007
Reputation Points: 10
Solved Threads: 0
 

Yes, that would be just fine I would imagine. You don't show the rest of the try block, but be sure to close the statement and connection in a finally{} clause so you don't chew up your database resources.

Ezzaral
Posting Genius
Moderator
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You