DEV Community

Hans
Hans

Posted on • Updated on

Connect to postgresdatabase with JAVA

Feel free to put variables and dbConnection() in another class.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/*

public class DatabaseConnection {

Connection connection;
String url = "jdbc:postgresql://localhost:5432/databasename";
String user = "username";
String password = "yourpassword";

public static void main(String[] args) throws ClassNotFoundException {
    DatabaseConnection db = new DatabaseConnection();
    db.dbConnection();
}

public Connection dbConnection() {
    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        DriverManager.getConnection(url, user, password);
        JOptionPane.showMessageDialog(null, "connected");

    } catch (SQLException ex) {
        Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null, "Failed to connect");
    }
    return connection;
}
Enter fullscreen mode Exit fullscreen mode

}

Discussion (0)