使用jdbc在java中创建单例连接对象

时间:2016-02-05 05:48:28

标签: java jdbc singleton

我正在尝试使用单例设计模式创建连接对象。这是正确的方法。请帮助我采取适当的方式。

package com.cisco.installbase.hiveconnector;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Connection;


public class CreateConnection {

        private static Connection connection = null;
        static final String drivername = "org.apache.hive.jdbc.HiveDriver";
        private static CreateConnection instance;

        private CreateConnection() {

            try{
                Class.forName(drivername);
                connection = DriverManager.getConnection("jdbc:hive2://hddev-c01-edge-01:50045/","phodisvc","B1GD4T4dev");
            }catch(ClassNotFoundException e){
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }

    }

        public static CreateConnection getInstance()
        {
            if(instance == null)
            {
                instance = new CreateConnection();
            }

            return instance;
        }
}

1 个答案:

答案 0 :(得分:0)

以我的示例为例。 (只需将URL,用户名和密码替换为您的),

public class DatabaseConnection {

public static Connection con = null;

public static void dbConnect(String drv, String url, String usr, String pwd) {

    // CHARGEMENT DU PILOTE
    try {
        Class.forName(drv);
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // CONNEXION BDD
    try {
        con = DriverManager.getConnection(url, usr, pwd);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}