public static ArrayList<User_Database> getUsername() {
ArrayList<User_Database> list_Username = new ArrayList<User_Database>();
try {
Class.forName(driver);
String sql = "SELECT user_name FROM users";
Connection connect = DriverManager.getConnection(url, user, password);
Statement state = connect.createStatement();
ResultSet rs = state.executeQuery(sql);
while (rs.next()) {
String user_name = rs.getString("user_name");
User_Database userDB = new User_Database(user_name);
list_Username.add(userDB);
System.out.printf(" %s \n", user_name);
}
rs.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
return list_Username;
}
public static void createNewUser(User_Database us) {
getAllUser();
try {
Class.forName(driver);
Connection connect = DriverManager.getConnection(url, user, password);
Statement state = connect.createStatement();
String sql = "INSERT INTO users VALUES (0, '" + us.user_name + "' , '" + us.user_password + "' , '"
+ us.email + "') ";
if (getAllUser().equals(us.user_name)) {
System.out.println("Username not available");
} else {
state.executeUpdate(sql);
state.close();
System.out.println("Insert Database Success");
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
}
答案 0 :(得分:0)
你正在呼叫getAllUser()
而我不知道是做什么的。假设您想要调用getUsername()
,这是您在此处提供的方法,它会在ArrayList<User_Database>
中返回您在数据库中拥有的所有用户名。
执行if (getAllUser().equals(us.user_name))
时,您尝试将ArrayList与String进行比较,这是错误的。请在下面的代码中找到更正:
public static void createNewUser(User_Database us) {
try {
Class.forName(driver);
Connection connect = DriverManager.getConnection(url, user, password);
Statement state = connect.createStatement();
String sql = "INSERT INTO users VALUES (0, '" + us.user_name + "' , '" + us.user_password + "' , '"
+ us.email + "') ";
boolean isUnique = true;
for(User_Database user: getUsername()) {
if(user.user_name.equals(us.user_name)) {
isUnique = false;
break;
}
}
if (!isUnique) {
System.out.println("Username not available");
} else {
state.executeUpdate(sql);
state.close();
System.out.println("Insert Database Success");
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
}
其他说明
另一个重要的考虑因素:
希望它有所帮助。