查询MySQL数据库并将整个列存储在ArrayList中

时间:2016-12-10 20:21:57

标签: java mysql authentication jdbc arraylist

我正在制作一个简单的登录表单,在那里我将查询数据库中的用户和密码并保存所有这些(这可能不是最好/最安全的方法,但我还在学习,我不想要高级在arraylists中,然后能够通过使用它们的索引来比较它们(如果索引相同,那么它将关联为同一个帐户)。我可以让查询工作,但我不能将行值逐个存储在列表中...使用我的代码,我可以使用第一个帐户登录,但其他人不工作。有人可以解释我如何做到这一点(尽量不要立即准备好代码,我想学习)。

2 个答案:

答案 0 :(得分:0)

嘿,如果我没有错,你看起来是java的新手,这里是从Mysql数据库中提取所有用户及其密码需要遵循的一系列步骤。

Step-1  Establish the connection with your databases and table.
Step-2  Use the ResultSet interface of JDBC API to query the database for users and thier passwords.
Step-3  Get the users from ResultSet and put it into one arrayList called User using the add method of arraylist as:- arraylistobj.add(user).
Steps-4 Now Get the passwords from resultSet into second arrayList called Passwords using the add method arraylistobj.add(password).
Steps-5 As you mentioned you want to compare arraylist objects here is a Sample code:

   for (int i = 0; i < list.size(); i++) {
     for (int j = i+1; j < list.size(); j++) {
         // compare list.get(i) and list.get(j)
    }
 }

Instead of using two arraylist's one for storing users from database and other for storing passwords,
it is much better to use Maps if you are familiar with as the store data in key value pair, 
in this example user could be the key and passwords could be the values associated with the keys.

答案 1 :(得分:0)

我并不完全清楚你想要完成什么,但请看下面的例子。我建议创建一个可以存储用户名和密码值的User对象,并为User创建一个ArrayList。您可以使用列索引来获取值。如果有任何问题或您有其他标准,请告诉我。

public class DBExample {

private static final String USERNAME = "";
private static final String PASSWORD = "";
private static final String CONN_STRING = "";

private static Connection getConnection() throws SQLException {
    return DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
}

public static List<User> processQuery(String sql){

    List<User> results = new ArrayList<>();

    try (
            Connection conn = getConnection();
            Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            ResultSet rs = stmt.executeQuery(sql)
    ) {

        while(rs.next()) {
            results.add(new User(rs.getString(1), rs.getString(2)));
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }

    return results;
}
}

用户类:

public class User {

private String username;
private String password;

public User(String username, String password) {
    this.username = username;
    this.password = password;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

}