Building a Desktop Application with JavaFX and SQL Server
Desktop apps are still a great way to learn how software is structured. In this post I explain how a **JavaFX** application can talk to **SQL Server** to manage student information. ## The layers A clean project separates responsibilities: | Layer | Job | |---|---| | **View (FXML)** | Describes the screens: tables, forms, buttons | | **Controller** | Handles clicks and input, calls the data layer | | **DAO / Repository** | Runs SQL queries | | **Database** | Stores the data in SQL Server | Keeping SQL out of controllers makes the code easier to test and change. ## Connecting to SQL Server Add the Microsoft JDBC driver to your project, then open a connection:
String url = "jdbc:sqlserver://localhost:1433;databaseName=SchoolDB;encrypt=true;trustServerCertificate=true";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
// use the connection
}Read the username and password from a config file or environment variable, never from source code. ## A simple DAO
public List<Student> findAll() throws SQLException {
String sql = "SELECT id, name, email FROM students ORDER BY name";
List<Student> list = new ArrayList<>();
try (Connection conn = Database.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
list.add(new Student(rs.getInt("id"), rs.getString("name"), rs.getString("email")));
}
}
return list;
}