import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException; public class ConnectDemo {
public enum MyEnumSingleton { connectionFactory;
private Connection conn; private MyEnumSingleton() {
try {
String url = "jdbc:mysql://localhost:3306/mydb";
String name = "root";
String password = "";
String Driver = "com.mysql.jdbc.Driver"; Class.forName(Driver); conn = DriverManager.getConnection(url, name, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace(); } catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public Connection getConn() {
return conn;
} } public static Connection getConn() {
return MyEnumSingleton.connectionFactory.getConn();
} }
使用枚举类时,构造方法会被自动调用。
再修改一下,降低一下耦合度,将建立连接的四大参数改成在配置文件中获取
首先在项目目录下建立一个配置文件
把参数添加进去
变成从配置文件中读取参数,这样修改的话只用修改配置文件就可以了
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties; public class ConnectDemo {
public enum MyEnumSingleton { connectionFactory;
private Connection conn; private MyEnumSingleton() {
try {
InputStream in=Connection.class.getClassLoader()
.getResourceAsStream("dbconfig.properties");
Properties pro=new Properties();
pro.load(in);
String url = pro.getProperty("url");
String name = pro.getProperty("name");
String password =pro.getProperty("password");
String Driver = pro.getProperty("DriverClassName"); Class.forName(Driver); conn = DriverManager.getConnection(url, name, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace(); } catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
} public Connection getConn() {
return conn;
} } public static Connection getConn() {
return MyEnumSingleton.connectionFactory.getConn();
} }