如何通过按钮单击移动Resultset光标,并在文本字段中显示数据?

时间:2018-03-13 04:59:46

标签: sqlite javafx cursor fxml resultset

所以,我正在创建一个桌面银行应用程序。它没有太严重,我只是想练习并变得更好。

// Method I use to get a connection. I know this works.
public static Connection getConnection() throws SQLException {
    String sCon = "jdbc:sqlite:banking.sqlite";
    Connection connection = DriverManager.getConnection(sCon);
    return connection;
}
.
..
... 
.....Other code

方法我尝试用来创建和操作结果集中的数据 我认为这个问题从这里开始。使用此代码,我只能返回结果集的一行,只返回最后一行。

public static Customers getAccounts(Customers c) {

    String query = "select RowCount, Customers.Account_Number, "
            + "Customers.First_Name, Last_Name, Address, "
            + "Phone_Number, Accounts.Balance "
            + "from Customers "
            + "join Accounts ";
    try (Connection connection = getConnection();
            PreparedStatement ps = connection.prepareStatement(query);
            ResultSet rs = ps.executeQuery()) {

        while (rs.next()) {

            String fName = rs.getString("First_Name");
            String lName = rs.getString("Last_Name");
            String address = rs.getString("Address");
            String phone = rs.getString("Phone_Number");
            String accNum = rs.getString("Account_Number");
            String balance = rs.getString("Balance");


            c.setFirstName(fName);
            c.setLastName(lName);
            c.setAddress(address);
            c.setPhoneNumber(phone);
            c.setAccountNumber(accNum);
            c.setBalance(balance);

        }
        return c;
    } catch (SQLException e) {
        System.err.println(e);
    }
    return null;
}
}

这是链接到我用来执行我尝试尝试的按钮的方法。它是Controller类的一部分。我相信这种方法也是问题的一部分。有任何想法吗?谢谢你们所做的一切。该网站对社区真正有益。

public void next() {
   Customers c = new Customers();
   DBInterface.getAccounts(c);

    firstNameF2.setText(c.getFirstName());
    lastNameF2.setText(c.getLastName());
    addressF2.setText(c.getAddress());
    phoneNumberF2.setText(c.getPhoneNumber());
    accNumF.setText(c.getAccountNumber());
    balanceF.setText(c.getBalance());

}

1 个答案:

答案 0 :(得分:1)

如果您希望获得多个Customers个对象,那么您肯定应该返回一个列表。

public static List<Customers> getAccounts() {
    // Whatever you originally had...

    final List<Customers> ret = new ArrayList<>();

    while (rs.next()) {
        String fName = rs.getString("First_Name");
        String lName = rs.getString("Last_Name");
        String address = rs.getString("Address");
        String phone = rs.getString("Phone_Number");
        String accNum = rs.getString("Account_Number");
        String balance = rs.getString("Balance");

        final Customers cust = new Customers();

        cust.setFirstName(fName);
        cust.setLastName(lName);
        cust.setAddress(address);
        cust.setPhoneNumber(phone);
        cust.setAccountNumber(accNum);
        cust.setBalance(balance);

        ret.add(cust);
    }

    return ret;
}

我删除了关于传递Customers实例的部分(最终会传递给List<Customers>。如果你真的需要这样做,你可以重新添加并执行所有操作必要的检查。