简体   繁体   中英

Returning the Connection from JDBC into a main method of Java?

Is it possible to return the type Connection? And use it as a method passed by reference through out the program? I find it makes the database interaction a lot easier if it is passed as a method.

public static Connection database(String database, String username, String password) {
        String url = "jdbc:postgresql:" + database;

        //LOAD DRIVER
        try {
            Class.forName("org.postgresql.Driver");
        } 
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }           

        //CONNECT TO DATABASE
        try {
            Connection conn = DriverManager.getConnection(url, username, password);
            return conn;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;            
}

public static void main(String[] args) {

    db = database("java_jdbc", "admin", "fake_password_1234");      
}

You can do that.

Just remember to invoke close() on the connection to release its resources when done.

package mySystem;

import java.sql.*;
import javax.swing.*;

public class MySqlConnector {

    Connection conn = null;

    public static Connection ConnectDB() {

        try {
            Class.forName("com.mysql.jdbc.Driver"); //register jdbc driver
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/inventory_db", "root", "");
            // JOptionPane.showMessageDialog(null, "Connected to db");
            return conn;

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
            return null;
        }

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM