String classDriverName = "com.mysql.jdbc.Driver";
Class.forName(classDriverName);
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","123");
Statement stmt = conn.createStatement();
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名和密码,格式:姓名,密码");
String line = sc.nextLine();
String[] arr = line.split(",");
String name = arr[0];
String password = arr[1];
ResultSet rs = stmt.executeQuery("select * from user where username = '"+name+"' and password = '"+password+"'");
if(rs.next()) {
System.out.println(rs.getString("username")+"登录成功");
}
else {
System.out.println("登录失败");
}
rs.close();
stmt.close();
conn.close();
以上是我代码,我的思路是根据用户输入的用户名和密码进行查表,假如rs集合是空,代表用户输入的用户名和密码不正确。
面试老师说我这个不行。
一定要以下做法:
String classDriverName = "com.mysql.jdbc.Driver";
Class.forName(classDriverName);
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","123");
Statement stmt = conn.createStatement();
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名和密码,格式:姓名,密码");
String line = sc.nextLine();
String[] arr = line.split(",");
String name = arr[0];
String password = arr[1];
ResultSet rs = stmt.executeQuery("select * from user");
while(rs.next()) {
if(rs.getString("username").equals(arr[0]) && rs.getString("password").equals(arr[1])) {
System.out.println("登录成功");
break;
}
else {
System.out.println("登录失败");
break;
}
}
这个代码我后面看了下,还是错的。
第一行记录不匹配为什么就直接说错了?你匹配的才是第一行记录呢。
要换这种思路:也是应该这样做啊
String classDriverName = "com.mysql.jdbc.Driver";
Class.forName(classDriverName);
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","123");
Statement stmt = conn.createStatement();
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名和密码,格式:姓名,密码");
String line = sc.nextLine();
String[] arr = line.split(",");
String name = arr[0];
String password = arr[1];
ResultSet rs = stmt.executeQuery("select * from user");
boolean flag = false;
while(rs.next()) {
if(rs.getString("username").equals(arr[0]) && rs.getString("password").equals(arr[1])) {
flag = true;
break;
}
}
if(flag) {
System.out.println("登录成功");
}
else {
System.out.println("登录失败");
}
我就想问下,我自己的做法有错嘛?有存在弊端?
|