赞
踩
单例的数据库连接类:
import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.FileInputStream; import java.sql.Connection; import java.util.Properties; public class Singleton { // 创建单例对象 private static Singleton singleton; // 创建数据库获取连接的对象 private static Connection singletonConnection = null; // 将构造方法私有化,防止外部new public Singleton() throws Exception { singletonConnection = Singleton.getConnection(); } private static Connection getConnection() throws Exception { Properties prop = new Properties(); prop.load(new FileInputStream("src\\main\\resources\\jdbc.properties")); DataSource dataSource = DruidDataSourceFactory.createDataSource(prop); Connection singletonConnection = dataSource.getConnection(); return singletonConnection; } // 对外提供实例化的方法 public static Connection getInstance() throws Exception { if (singleton == null) { singleton = new Singleton(); } return singletonConnection; } }
测试类:
package com.gy.config; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; public class test { public static void main(String[] args) throws Exception { Connection instance = Singleton.getInstance(); Connection instance1 = Singleton.getInstance(); Connection instance2 = Singleton.getInstance(); System.out.println(instance); System.out.println(instance1); System.out.println(instance2); System.out.println("============================"); Statement statement = instance.createStatement(); String sql="select * from user"; ResultSet resultSet = statement.executeQuery(sql); List<User> users=new ArrayList<>(); while (resultSet.next()){ String name = resultSet.getString(1); String password = resultSet.getString(2); int id = resultSet.getInt(3); User user = new User(name, password, id); users.add(user); } System.out.println(users); } }
运行结果:(成功返回单例对象)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。