JdbcUtils1.0版本

1.首先编写dbconfig.properties配置文件
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/student
username=root
password=123
2.编写JdbcUtil1.java工具类
package cn.cmlx.jdbcutils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
/**
* version1.0
* @author 赤名莉香
*
*/
public class JdbcUtil1 {
private static Properties props = null;
//只在JdbcUtil1类被加载时执行一次
static {
//给props进行初始化,即加载dbconfig.properties文件到props对象中
try {
InputStream in = JdbcUtil1.class.getClassLoader().getResourceAsStream("dbconfig.properties");
props = new Properties();
props.load(in);
}catch (IOException e) {
throw new RuntimeException(e);
}
//加载驱动类
try {
Class.forName(props.getProperty("driverClassName"));
}catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public static Connection getConnection() throws SQLException{
//得到Connection
return DriverManager.getConnection(props.getProperty("url"), props.getProperty("username"), props.getProperty("password"));
}
}
3.应用
package cn.cmlx.test;
import java.sql.Connection;
import java.sql.SQLException;
import org.junit.Test;
import cn.cmlx.jdbcutils.JdbcUtil1;
public class Test2 {
@Test
public void func1() throws SQLException {
Connection con = JdbcUtil1.getConnection();
System.out.println(con);
Connection con1 = JdbcUtil1.getConnection();
System.out.println(con1);
}
}