第一步:導入兩個jar包

第二步:創建一個properties文件

第三步:在properties文件中添加配置:連接驅動、數據庫名字、數據庫用戶名和密碼等
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql:///ManageSys?useUnicode=true&characterEncoding=utf-8&useSSL=false
username=root password=admin123 initialSize=5 maxActive=10 maxWait=3000 maxIdle=6 minIdle=3
第四步:創建連接池對象
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JdbcUtil {
// 創建數據源對象
private static DataSource dataSource;
static {
// 新建一個配置文件對象
Properties properties = new Properties();
// 通過類加載器找到文件路徑,讀配置文件
InputStream inputStream = JdbcUtil.class.getResourceAsStream("/d.properties");
// 加載屬性文件
try {
properties.load(inputStream);
// 創建連接池對象
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 從連接池中獲取連接
* */
public static Connection getConnect(){
Connection con = null;
try {
con = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
/*
* 關閉資源
* */
public static void close(Connection connection, Statement statement, ResultSet resultSet){
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
最后測試一下效果:
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
Connection connection = JdbcUtil.getConnect();
try {
DatabaseMetaData databaseMetaData = connection.getMetaData();
System.out.println(databaseMetaData.getURL() + ","
+ databaseMetaData.getUserName() + ","
+ databaseMetaData.getDriverName());
} catch (SQLException e) {
e.printStackTrace();
}
}
}

