gpt4 book ai didi

java - 如何从mysql数据库读取数据并将其插入到已实现的哈希表中?

转载 作者:行者123 更新时间:2023-11-29 16:10:17 24 4
gpt4 key购买 nike

我需要修改我的程序以从 mysql 数据库读取用户名和密码并将其插入到哈希表中,但我无法将其插入到哈希表中。我做错了什么?

private static final Map<String, String> accounts = new Hashtable<>();
public static void main(String args[]){
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb","root","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from account");
accounts.put(rs.getString("username"),
rs.getString("password"));
while(rs.next())
System.out.println(rs.getString("username") + " " +
rs.getString("password"));
con.close();
}
catch(Exception e){
System.out.println(e);
}

}

最佳答案

参见here .

此行不起作用:

accounts.put(rs.getString("username"), 
rs.getString("password"));

因为您尚未断言 ResultSet 中包含任何数据。

即在从当前行中提取数据之前,您至少必须调用 rs.next() (以确保其中有数据)。

关于java - 如何从mysql数据库读取数据并将其插入到已实现的哈希表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55320658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com