第一步:src文件夹右键-new-other-general-file-文件dbconfig.properties 内容如下:
driver=com.mysql.jdbc.Driver
dburl=jdbc\:mysql\://localhost\:3306/jsp_db
user=root
password=
第二步:新建ConnectionFactory.java文件内容如下:
package com.jikexueyuan.util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
public classConnectionFactory{
private staticString driver;
private staticString dburl;
private staticString user;
private staticString password;
private staticfinalConnectionFactory factory=newConnectionFactory();
privateConnection conn;
//静态代码块只会执行一次
static {
Properties prop=newProperties();
try{
InputStream in=ConnectionFactory.class.getClassLoader()
.getResourceAsStream("dbconfig.properties");
prop.load(in);
}catch(Exception e){
System.out.println("==========配置文件读取错误============");
}
driver = prop.getProperty("driver");
dburl = prop.getProperty("dburl");
user = prop.getProperty("user");
password = prop.getProperty("password");
}
privateConnectionFactory(){
}
publicstaticConnectionFactorygetInstance(){
return factory;
}
publicConnectionmakeConnection(){
try{
Class.forName(driver);
conn =DriverManager.getConnection(dburl, user, password);
}catch(Exception e){
e.printStackTrace();
}
return conn;
}
}
第三步:新建ConnectionFactoryTest.java文件内容如下:
package com.jikexueyuan.test;
import java.sql.Connection;
import com.jikexueyuan.util.ConnectionFactory;
public class ConnectionFactoryTest {
public static void main(String[] args) throws Exception{
ConnectionFactory cf = ConnectionFactory.getInstance();
Connection conn = cf.makeConnection();
System.out.println(conn.getAutoCommit());
}
}
右键run as- java application控制台输出 true