0% found this document useful (0 votes)
11 views2 pages

PostgreSQL Java Connection Example

Uploaded by

bonprix1982
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

PostgreSQL Java Connection Example

Uploaded by

bonprix1982
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

etape: ajout les dependencies

<dependency>
<groupId>[Link]</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.5</version>
</dependency>
etape 2: creation la classe de la connexion à la base de donnée

package [Link];

import [Link];
import [Link];
import [Link];

public class Database {


private static final String URL = "jdbc:postgresql://localhost:5432/person";
private static final String USER = "postgres";
private static final String PASSWORD = "123456789";

public static Connection getConnection() throws SQLException {


return [Link](URL, USER, PASSWORD);
}
}

etape 3: creation la classe des setter et getter

package [Link];

public class Person {


private int id;
private String nom;
private String prenom;

public Person(int id, String nom, String prenom) {


[Link] = id;
[Link] = nom;
[Link] = prenom;
}

public int getId() { return id; }


public String getNom() { return nom; }
public String getPrenom() { return prenom; }
}

etape 4: creation de la classe view

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];
import [Link];

public class Main extends Application {

private TableView<Person> table = new TableView<>();

@Override
public void start(Stage stage) {
TableColumn<Person, Integer> idCol = new TableColumn<>("ID");
[Link](new PropertyValueFactory<>("id"));

TableColumn<Person, String> nomCol = new TableColumn<>("Nom");


[Link](new PropertyValueFactory<>("nom"));

TableColumn<Person, String> prenomCol = new TableColumn<>("Prénom");


[Link](new PropertyValueFactory<>("prenom"));

[Link]().addAll(idCol, nomCol, prenomCol);

VBox vbox = new VBox(table);


Scene scene = new Scene(vbox, 400, 300);
[Link](scene);
[Link]("Liste des personnes");
[Link]();

chargerDonnees();
}

private void chargerDonnees() {


ObservableList<Person> data = [Link]();
try (Connection conn = [Link]();
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT id, nom, prenom FROM
person")) {

while ([Link]()) {
[Link](new Person(
[Link]("id"),
[Link]("nom"),
[Link]("prenom")
));
}
[Link](data);
} catch (SQLException e) {
[Link]();
}
}

public static void main(String[] args) {


launch(args);
}
}

Common questions

Powered by AI

The chargerDonnees method queries the database for records and populates the TableView. It opens a database connection, executes an SQL select statement, iterates over the ResultSet, and constructs Person objects for each record. These are added to an ObservableList, which is then assigned to the TableView. This integration allows dynamic updating of table data as it reflects the contents of the database. Any SQLException is caught and printed, ensuring application robustness: try (Connection conn = Database.getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT id, nom, prenom FROM person")) { [...] } catch (SQLException e) { e.printStackTrace(); } .

The Person class acts as a data model representing an entry in the database. It has fields mirroring the database columns: id, nom, and prenom. Constructor methods initialize these fields, and getter methods provide access. This design allows the TableView to easily bind to these fields via PropertyValueFactory, ensuring that each row in the TableView corresponds directly to a database record: public class Person { private int id; private String nom; private String prenom; [...] } .

A Postgres database connection in Java is established using the DriverManager.getConnection method. You must provide the database URL, username, and password. The connection code must handle SQLException, which could occur during the attempt to connect. This is implemented as follows: public static Connection getConnection() throws SQLException { return DriverManager.getConnection(URL, USER, PASSWORD); } .

Setting up a JavaFX application to display database records involves creating a TableView component, defining TableColumns for each data field, and using an ObservableList to hold the data. In the JavaFX application, initialize the table and columns in the start method. Use PropertyValueFactory to bind table columns to the fields in your data class (e.g., ID, Nom, Prénom). The data is populated from the database using an SQL query and added to the ObservableList, which is then set as the table's items. Here's a snippet of setting up columns: TableColumn<Person, Integer> idCol = new TableColumn<>("ID"); idCol.setCellValueFactory(new PropertyValueFactory<>("id")); [...].

The dynamic updates are facilitated by using ObservableList as the data model for TableView. JavaFX automatically listens for changes within this list and updates the UI components accordingly. After retrieving data from the database, the ObservableList is refreshed, and the TableView's setItems method is called with the new data, reflecting any modifications in real-time. The use of PropertyValueFactory further assists by dynamically linking UI elements to data properties .

The VBox layout in JavaFX is used to arrange UI components vertically. In the application displaying a database table, VBox is utilized to hold the TableView. This layout simplifies adding multiple tables or other components below each other within the GUI. The VBox instance is passed as the root node to the Scene object, defining the structure of the application window: VBox vbox = new VBox(table); Scene scene = new Scene(vbox, 400, 300).

Efficient management of database connections entails using a connection pool to reduce overhead and improve performance. Handling SQLExceptions robustly ensures that the application does not crash due to transient issues. Connections should be instantiated only when necessary and closed promptly within a finally block or using the try-with-resources statement to prevent resource leaks: try (Connection conn = Database.getConnection()) { [...] } catch (SQLException e) { [...] } .

PropertyValueFactory in JavaFX enables automatic data binding between Java class fields and TableView columns. It uses Java reflection to map column names to object properties, streamlining the rendering of data in TableView components. This mechanism is crucial in this application as it simplifies the presentation layer, ensuring that changes in the underlying dataset are automatically reflected in the UI: TableColumn<Person, String> nomCol = new TableColumn<>("Nom"); nomCol.setCellValueFactory(new PropertyValueFactory<>("nom")).

To establish a connection to a PostgreSQL database in a Java project, you need to include the PostgreSQL JDBC driver as a dependency. Specifically, you should add the following dependency in your project configuration: <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.7.5</version> </dependency> .

Potential risks include incorrect connection strings, authentication failures, and database unavailability. Debugging strategies involve validating the connection URL, credentials, checking network issues, and reviewing server logs for specific error messages. SQLExceptions provide insights into connection failures, and implementing comprehensive logging within a try-catch block helps trace issues effectively. Structural inspections of SQL syntax and validating the existence of database tables and columns are essential .

You might also like