Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking Records from Database Java

Tags:

java

jsp

jdbc

I have a Table Like below

enter image description here

I run a Query to get Values in Table as Below

SELECT Id, UserName, UserId, Password, 
       CASE Status WHEN 1 THEN 'Active' ELSE 'Inactive' END AS Status 
  FROM users

Now I Java code for the Above Query is as below.

    String[] arrUsersList[] = new String[100][5];
    String[] arrUsersTem    =  new String[5];

    pstmt = conn.createStatement(rs.TYPE_FORWARD_ONLY, rs.CONCUR_READ_ONLY);
    rs    = pstmt.executeQuery(strSQL);


    while(rs.next())
    {   
        arrUsersTem[0] = rs.getString("Id");
        arrUsersTem[1] = rs.getString("UserName");
        arrUsersTem[2] = rs.getString("UserId");
        arrUsersTem[3] = rs.getString("Password");
        arrUsersTem[4] = rs.getString("Status");

        arrUsersList.add(arrUsersTem);
    }

My Question is

I know I should use two dimensional array for getting the values from Recordset. I also know I am Doing it wrong way.What is the right way of taking records from Result set for the above.

Is array right option or i should use ArrayList or Some thing else.

Thanks for Reply.

like image 915
Java Beginner Avatar asked Jun 11 '26 14:06

Java Beginner


2 Answers

Java is OOP language, so common way is to create class describing entities of your table and form Collection with this class objects

class Account {

    private long id;
    private String userName;
    private String userId;
    private String password;
    private boolean status;

    // getters, setters
}

List<Account> accountList = new ArrayList();
Account account;

while(rs.next()) {   

    account = new Account();
    account.setId(rs.getLong("Id"));
    account.setUserName(rs.getString("UserName"));
    account.setUserId(rs.getString("UserId"));
    account.setPassword(rs.getString("Password"));
    account.setStatus(rs.getBoolean("Status"));

    accountList.add(account);
}
like image 121
bsiamionau Avatar answered Jun 13 '26 02:06

bsiamionau


You should create a User bean that contains fields for each of your database columns. Then create a List of User beans and do this:

List<User> users = new ArrayList<User>();
while(rs.next()) {   
        User user = new User();
        user.setId(rs.getString("Id"));
        user.setUsername(rs.getString("UserName"));
        //More fields here


        users.add(user);
    }

You will then be left with a list of Users rather than a confusing 2d array

like image 31
cowls Avatar answered Jun 13 '26 02:06

cowls



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!