所以,我正在创建一个桌面银行应用程序。没什么大不了的,我只是想练习一下,变得更好。
// 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
方法 I 尝试用于创建和操作结果集中的数据。
我认为问题从这里开始。使用此代码,我只能返回结果集的一行,并且只能返回最后一行。
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;
}
}
这是链接到我用来执行我尝试尝试的按钮的方法。它是控制器类的一部分。我相信这种方法也是问题的一部分。有什么想法吗?感谢你们所做的一切。这个网站对社区来说是一个真正的好处。
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());
}
如果您希望获得多个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>
.如果您确实需要这样做,您可以重新添加并进行所有必要的检查。