Java ArrayList显示来自数据库的所有结果

Java ArrayList显示来自数据库的所有结果,java,mysql,jdbc,arraylist,Java,Mysql,Jdbc,Arraylist,我想从mysql数据库中获取一行。但是我的程序打印数据库中的所有行。我不确定出了什么问题。你能帮我吗 public class ScreenBalance { // show all records public static ArrayList<String> showOnScreenBalance() throws Exception { LoginVerification.login(); try { Connection con = Con

我想从mysql数据库中获取一行。但是我的程序打印数据库中的所有行。我不确定出了什么问题。你能帮我吗

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;
}

}您必须定义要打印的数据库表的哪一行。为此,可以在sql语句中定义WHERE子句

PreparedStatement statement = con.prepareStatement("SELECT ClientID, Money FROM BankDB.Info WHERE some_condition" );
例如:

对于结果数为1的情况,WHERE条件也必须设计为这样的方式(只有一行具有这样的列值),否则程序无法知道预期结果


希望有帮助:)

您的查询将选择表中的所有行。您希望发生什么?您的第二个类不会在第一个类中看到(局部)变量,因为您没有将它们传递给第二个类。你可以使用你的方法
shownscreenbalance(stringuserid)
并在where子句中使用它来选择正确的用户余额。哇,谢谢,这就是我要找的:)你能纠正我的shownscreenbalance方法吗?我自己很难做到这一点实际上最简单的方法可能是让您的
login()
返回
userId
。然后您可以在
String user=LoginVerification.login()上获得它。我不会为你写代码,因为这是你的家庭作业。
PreparedStatement statement = con.prepareStatement("SELECT ClientID, Money FROM BankDB.Info WHERE some_condition" );
PreparedStatement statement = con.prepareStatement("SELECT ClientID, Money FROM BankDB.Info WHERE ClientID='some_value'" );