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;
/*
- Need library Postgresql -> installed in library
- Simple connection to postgres
- https://www.tutorialspoint.com/postgresql/postgresql_java.htm */
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;
}
}
Top comments (0)