0
我想從mysql數據庫獲取一行。但我的程序打印來自數據庫的所有行。我不確定什麼是錯的。你可以幫幫我嗎?ArrayList顯示來自數據庫的所有結果
public class ScreenBalance {
// show all records
public static ArrayList<String> showOnScreenBalance() throws Exception {
LoginVerification.login();
try {
Connection con = ConnectionDB.getConnection();
PreparedStatement statement = con.prepareStatement("SELECT ClientID, Money FROM BankDB.Info");
ResultSet result = statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
System.out.print("\nID\t\tAmount\t\n");
while (result.next()) {
System.out.print(result.getString("ClientID"));
System.out.print("\t");
System.out.print(result.getString("Money"));
System.out.print("\t");
array.add(result.getString("Money"));
}
System.out.println();
return array;
} catch (Exception e) {
System.out.println(e);
}
return null;
}
以下是我希望選擇一行的第二堂課。但它不能正常工作。我輸入clientID +客戶端密碼,爲什麼我的方法'showOnScreenBalance'沒有看到它?
public class LoginVerification {
private static boolean loggedIn = false;
public static void login() throws Exception {
System.out.println("ATM Machine v 1.0, Welcome user.");
if(loggedIn){
//do nothing, user already logged in
return;
}
Scanner input = new Scanner(System.in);
System.out.println("Please enter USER ID:");
String userId = input.nextLine();
System.out.println("Please enter PIN CODE:");
String pass = input.nextLine();
try {
Connection con = ConnectionDB.getConnection();
String sql = "SELECT COUNT(*) FROM Info WHERE ClientID = ? AND ClientPass = ?";
PreparedStatement posted = con.prepareStatement(sql);
posted.setString(1, userId);
posted.setString(2, pass);
ResultSet resultSet = posted.executeQuery();
resultSet.next();
int rowCount = resultSet.getInt(1);
if (rowCount == 1) {
loggedIn = true;
System.out.println("LOGIN SUCCESSFUL");
Helper.showMainMenu();
} else {
loggedIn = false;
System.out.println("#LOGIN UNSUCCESSFUL, WRONG LOGIN OR PASSWORD");
System.out.println("\nTry again? \n1) yes \n2) no [quit]");
int choice = input.nextInt();
if (choice == 1) {
login();
} else {
System.exit(0);
}
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
您的查詢選擇表中的所有行。你期望發生什麼? – Kayaman
您的第二堂課不會在您的第一堂課中看到(本地)變數,因爲您沒有將它們傳遞給第二堂課。你可以使你的方法'showOnScreenBalance(String userid)'在where子句中用來選擇正確的用戶餘額。 – Kayaman
哇謝謝,這就是我在找:)可以請你糾正我的showOnScreenBalance方法嗎?我有麻煩去自己做 – damianm