封装一个简单的JDBC连接池
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import com.alibaba.druid.pool.DruidDataSource;
public class JDBCUtils {
private static String driver ;
private static String url;
private static String username;
private static String password;
private static DruidDataSource dds;
//读取配置文件
static {
readPropertues();
dds = new DruidDataSource();
dds.setDriverClassName(driver);
dds.setUrl(url);
dds.setUsername(username);
dds.setPassword(password);
//设置初始化数量,让连接池一开始就初始化连接,需要调用init()方法
dds.setInitialSize(8);
try {
dds.init();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
//读取配置文件
public static void readPropertues() {
Properties prop = new Properties();
String path = JDBCUtils.class.getResource("/").getPath();
FileInputStream fis = null;
try {
fis = new FileInputStream(path + "data.properties");
prop.load(fis);
driver = prop.getProperty("driver");
url = prop.getProperty("url");
username = prop.getProperty("userName");
password = prop.getProperty("passWord");
} catch (FileNotFoundException e) {
throw new RuntimeException("未找到配置文件");
} catch (IOException e) {
throw new RuntimeException("读取配置文件失败");
}
}
//获取连接
public static Connection getConnection() {
try {
return dds.getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
throw new RuntimeException("获取连接失败");
}
//关闭连接
public static void close(Connection connection) {
if(connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
throw new RuntimeException("关闭连接失败");
}
}
}
}
建立一个data.properties配置文件
url=jdbc:mysql://localhost:3306/manger?useUnicode=true&characterEncoding=utf-8
userName=
passWord=
driver=com.mysql.jdbc.Driver
mysql8版本的数据库
JDBC driver 由“com.mysql.jdbc.Driver”改为“com.mysql.cj.jdbc.Driver”
相应的驱动包应该改为:
mysql-connector-java-8.0.11.jar
避免导致连接失败
我本人使用的mysql版本为5.6.44
druid jar包为druid-1.0.12.jar
如果你使用的是高版本的mysql数据库请自行下载对应的druid jar包