用线程池来进行数据库和jdbc的对接
- 这是一个连接数据库的工具类,通过它里面的方法可以直接实现和数据库的连接
/*
工具类:连接数据库的
*/
public class DBUtil {
private static BasicDataSource bds;
private static String url;
private static String driver;
private static String username;
private static String password;
private static int initial;
private static int max;
static {
try {
//数据库用的线程池
bds = new BasicDataSource();
//创建properties对象用于储存该类文件的的数据
Properties p = new Properties();
//创建inputstream对象读取该类文件数据
InputStream is = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
p.load(is);
//将读取的赋值给定义好的变量
url = p.getProperty("url");
driver = p.getProperty("driver");
username = p.getProperty("username");
password = p.getProperty("password");
initial = Integer.parseInt(p.getProperty("initial"));
max = Integer.parseInt(p.getProperty("max"));
//将变量的值赋值给数据库线程池
bds.setUrl(url);
bds.setUsername(username);
bds.setDriverClassName(driver);
bds.setPassword(password);
bds.setInitialSize(initial);
bds.setMaxActive(max);
} catch (IOException e) {
System.out.println("数据库获取信息出现异常");
e.printStackTrace();
}
}
public static Connection getConnection() {
//创建connection对象
Connection conn = null;
try {
//进行连接并把连接结果返回给connection对象
conn = bds.getConnection();
} catch (SQLException e) {
System.out.println("数据库连接异常");
e.printStackTrace();
}
return conn;
}
public static void closed(Connection conn) {
try {
conn.close();
} catch (SQLException e) {
System.out.println("数据库关闭异常");
e.printStackTrace();
}
}
public static void main(String[] args) {
Connection conn = getConnection();
System.out.println(conn);
System.out.println("数据库连接工具正常运行...............");
}
}
-
properties文件内容
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/newdb3?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC username=? password=? max=? initial=?