Return to site

☕2️⃣3️⃣ Java 23 Import module: All In One Import

· java23,java

With #Java module import, you import the entire module; there is no need to maintain a long list of import statements at the beginning of the file. #jdk23

package com.vv;
//The HOT stuff is the line just BELOW
import module java.sql;

public class Java23ModuleTryOut {

static final String DB_URL = "jdbc:postgresql://localhost:54320/postgres";
static final String USER = "postgres";
static final String PASS = "my_password";
static final String QUERY = "SELECT id, first, last, age FROM Employees";

public static void main(String[] args) {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
return;
}

// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(QUERY);) {

// Extract data from result set
while (rs.next()) {
// Retrieve by column name
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

I do a JDBC call to a PostgreSQL database where I ask to list the employees of the table employees.

And all the classes of java.sql are all imported in one shot with:

import module java.sql;

rather than 

import java.sql.Connection;import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

Nice! no?

find the complete code below:

find the article of Java champion A N M Bazlur Rahman on this topic: