0

是否可以返回类型连接?并将其用作通过引用传递整个程序的方法?我发现如果将其作为方法传递,它会使数据库交互变得容易得多。

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");      
}
4

2 回答 2

2

你可以这样做。

只需记住在完成后调用close()连接以释放其资源。

于 2012-04-14T23:05:54.657 回答
0
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;
        }

    }

}
于 2016-04-07T16:49:19.103 回答