我正在使用 JavaFX 创建一个基本的 GUI。我在 MySQL 中创建了一个数据库来存储数据。 (DBConnect) (连接器/j)
这是我第一次尝试连接两者以及使用 ResultSets/DBConnect
目前,我有 3 个类:我的 Game 类、我的 GameUI 类(主)和我的 DBConnect 类。
我试图在我的 GameUI 类中引用 ResultSet,该类最初是在 Game 类中声明的。
public class Game {
private static DBConnect dbc;
private static Connection conn;
public ResultSet rs;
int id;
String name;
float price;
String vendor;
int rating;
public Game() {
try {
conn = dbc.connect();
String SQL = "Select * from Person";
rs = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE).executeQuery(SQL);
System.out.println("list result set for record..");
printRs(rs);
} catch(SQLException ignore) {
}
}
我的用户定义的 moveNext() 方法:
public Game moveNext() {
Game g = new Game();
try {
if(rs.next() == false)
rs.previous();
g.setGameId(rs.getInt("gameId"));
g.setGameName(rs.getString("gameName"));
g.setPrice(rs.getFloat("price"));
g.setVendor(rs.getString("vendor"));
g.setRating(rs.getInt("rating"));
} catch(SQLException e) {
e.printStackTrace();
}
return g;
}
我试图在其中引用它的 GameUI 类:
public class GameUI extends Application {
private Button firstButton = new Button("First");
private Button createButton = new Button("Create");
private Button updateButton = new Button("Update");
private Button deleteButton = new Button("Delete");
private Button lastButton = new Button("Last");
private Button nextButton = new Button("Next");
private Button prevButton = new Button("Prev");
GridPane grid = new GridPane();
HBox hbox = new HBox(14);
private static DBConnect dbc;
private static Connection conn;
// private static
private Pane initButtons() {
hbox.getChildren().addAll(firstButton, createButton, updateButton, deleteButton, lastButton, nextButton, prevButton);
nextButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
Game.rs.moveNext();
}
});
return hbox;
}
我的问题是,我可以在 nextButton
事件处理程序(我的 GameUI 类)中引用我的 ResultSet (Game 类)还是必须声明一个新的结果集?
这是我的用户定义的 moveNext()
方法的正确位置,还是应该使用 next()
?
我将根据要求发布更多代码。
最佳答案
您可以进一步传递结果集,但这是不好的做法(请参阅 Is it Ok to Pass ResultSet? )。从我从您发布的代码中看到,这主要是应用程序不同部分的分层问题,应该将其分开:
数据库相关代码属于一层。其他层不应直接与数据库通信或处理任何数据库特定对象。为了实现这一点,DBConnection
类应该处理所有与数据库相关的内容。要将数据从数据库传递到其他层(反之亦然),您可以使用数据传输对象(DTO),它基本上是特定结果集的对象表示。通常这可以归结为每个数据库表一个 DTO。
然后你有一个中间层,我们称之为服务层,它用于从 UI 到数据库进行通信并进行一些计算。
最重要的是,您有应用程序所在的 UI 层。在这里,您必须考虑哪些操作属于该层以及哪些操作最好委托(delegate)给服务层。
另请参阅这篇维基百科文章:https://en.wikipedia.org/wiki/Multitier_architecture
关于mysql - 引用 ResultSet/使用 Next() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33589187/