- Why I need to use
Class.forName("org.postgresql.Driver");
and what is it stands for?
- Why my code work without it despite everywhere says that it wouldn't work without it? (I used it in empty project so
Class.forName("org.postgresql.Driver")
has not been executed there)
import java.sql.*;
public class Solution
{
public static void main(String[] args)
{
final String DATABASE_URL = "jdbc:postgresql://localhost:5432/postgres";
final String USER = "postgres";
final String PASSWORD = "123";
try
{
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
String sqlQuery = "SELECT * FROM students;";
try (Connection connection = DriverManager.getConnection(DATABASE_URL, USER, PASSWORD);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sqlQuery);
)
{
System.out.println("Connected successfully");
while (resultSet.next())
{
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
System.out.printf("name: %s, age: %d\n", name, age);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}