我尝试使用MySQL数据库验证java中的用户(登录)。我希望能够在控制台中执行此操作。这就是我到目前为止:我的主要课程 -
import java.util.Scanner;
public class main {
public static void main(String args[]){
if (args.length < 2)
return;
login meth = new login();
Scanner in = new Scanner(System.in);
String username;
String password;
System.out.println("");
System.out.println("Username: ");
username = in.next();
System.out.println("2. Account Holder");
password = in.next();
System.out.println("");
meth.loginDetails(username, password);
login checker = new login();
boolean rc = checker.loginDetails(args[0], args[1]);
System.out.println("The result is: " + Boolean.toString(rc));
in.close();
}
}
这是我的课程,我尝试连接数据库并进行查询。
import java.sql.*;
public class login {
public void databaseConnection(){ //swapping index a and index b around
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://localhost/loginTest","root", "");
System.out.println("Database is connected !");
conn.close();
}
catch(Exception e){
System.out.println("Do not connect to DB - Error:"+e);
}
}
static final String CONN_URL = "jdbc:mysql://localhost/loginTest";
static final String DB_USER = "root";
static final String DB_PASSWORD = "";
public boolean loginDetails(String accountNumber, String password){
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
boolean passwdOK = false;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(CONN_URL, DB_USER, DB_PASSWORD);
// Create and execute an SQL statement
String sqlst = "SELECT Password FROM customer " +
" WHERE Account Number = '" + accountNumber + "'";
stmt = con.createStatement();
rs = stmt.executeQuery(sqlst);
// Check the return data
if (rs.next()) {
String passwdSaved = rs.getString(1).trim();
if (passwdSaved.equals(password.trim()))
passwdOK = true;
}
rs.close();
stmt.close();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (con != null) try { con.close(); } catch(Exception e) {}
}
return passwdOK;
}
}
我的数据库名为Customer,单独的列称为帐号,密码。
在我运行该程序时,它立即被终止。没有显示任何打印行。
所以我的问题是我如何得到一个真或假的结果,用户名和密码是匹配的。如果它是假的,让他们重试,如果它的真正负载切换菜单?
答案 0 :(得分:1)
首先改变
boolean rc = checker.loginDetails(args[0], args[1]);
到
boolean rc = checker.loginDetails(username, password);
如果您没有使用参数运行此程序,则args [0]和args [1]将抛出ArrayIndexOutOfBoundException