随意将变量和dbConnection()放在另一个类中。
导入java.sql.Connection; 导入java.sql.DriverManager; 导入java.sql.SQLException; 导入java.util.logging.Level; 导入java.util.logging.Logger; 导入javax.swing.JOptionPane;
/ *
- Need library Postgresql -> installed in library
- Simple connection to postgres
- https://www.tutorialspoint.com/postgresql/postgresql_java.htm */
公共类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;
}
}