本文主要来说说三种 Java 中获取 mysql 连接的方式,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍:
第一种:传统的连接方式;
第二种:读取配置文件方式;
第三种:数据库连接池。
Maven工程,引依赖一、传统的连接方式:mysql mysql-connector-java8.0.18
Codes:
public class Demo1 {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// 1、注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 2、数据库连接基本信息url、user、password
String url = "jdbc:mysql://localhost:3306/seckill?useSSL=false&useUnicode=true&characterEncoding=UTF-8&useAffectedRows=true&nullCatalogMeansCurrent=true&allowMultiQueries=true&serverTimezone=GMT%2B8";
String user = "root";
String password = "123456";
// 3、获取连接
Connection conn = DriverManager.getConnection(url, user, password);
log.info(">>>>>>>>>>>>【{}】", conn);
}
打印效果如下:
二、读取配置文件方式首先在 resources目录下创建一个 db.properties 的配置文件,内容如下:
driver: com.mysql.cj.jdbc.Driver url:jdbc:mysql://localhost:3306/seckill?useSSL=false&useUnicode=true&characterEncoding=UTF-8&useAffectedRows=true&nullCatalogMeansCurrent=true&allowMultiQueries=true&serverTimezone=GMT%2B8 user:root password:123456
Codes:
public class Demo2 {
public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
// 1、读取配置文件
InputStream is = Demo2.class.getClassLoader().getResourceAsStream(" db.properties");
// 2、创建Properties对象
Properties pro = new Properties();
// 3、装载
pro.load(is);
// 4、解析
String driver = pro.getProperty("driver");
String url = pro.getProperty("url");
String user = pro.getProperty("user");
String password = pro.getProperty("password");
// 5、注册驱动获取连接
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, user, password);
log.info(">>>>>>>>>>>>【{}】", conn);
}
打印效果如下:
三、数据库连接池首先在 resources目录下创建一个 db.properties 的配置文件,内容如下:
driver: com.mysql.cj.jdbc.Driver url:jdbc:mysql://localhost:3306/seckill?useSSL=false&useUnicode=true&characterEncoding=UTF-8&useAffectedRows=true&nullCatalogMeansCurrent=true&allowMultiQueries=true&serverTimezone=GMT%2B8 user:root password:123456
Codes:
@Slf4j
public class Demo3 {
// 1、声明Druid连接池的对象
private static DruidDataSource dataSource;
public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
initDataSource();// 初始化连接池
try{// 查询数据
String sql = "select * from sec_kill";
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
long id = rs.getLong("sec_kill_id");
String name = rs.getString("name");
log.info(">>>>>>id:{},name:{}", id, name);
}
// 插入一个数据
String sql = "insert into userinfo (username, password)"+ "values(" +"'"+ "yy" +"'"+ "," +"'"+"123456"+"'"+")";
Connection connection = getConnect();// 在连接池里面获取连接对象
PreparedStatement ps = connection.prepareStatement(sql);// 预编译下SQL语句
int count = ps.executeUpdate();// 提交SQL语句
log.info(">>>>>>{}", count);// 打印受影响的行数(不为0说明执行了!)
}catch (Exception e){
log.info(">>>>>>>>>>>>", e);
}
}
// 初始化连接池
private static void initDataSource() {
try {
// 1、读取配置文件
InputStream is = Demo3.class.getClassLoader().getResourceAsStream(" db.properties");
// 2、创建Properties对象
Properties pro = new Properties();
// 3、装载
pro.load(is);
// 4、解析
dataSource = new DruidDataSource(); // 创建Druid连接池
dataSource.setDriverClassName(pro.getProperty("driver")); // 设置连接池的数据库驱动
dataSource.setUrl(pro.getProperty("url")); // 设置数据库的连接地址
dataSource.setUsername(pro.getProperty("user")); // 数据库的用户名
dataSource.setPassword(pro.getProperty("password")); // 数据库的密码
dataSource.setInitialSize(1); // 设置连接池的初始大小
dataSource.setMinIdle(1); // 设置连接池大小的下限
dataSource.setMaxActive(20); // 设置连接池大小的上限
}catch (Exception e){
log.info(">>>>>>>>>>>>", e);
}
}
//从连接池里面获取一个连接对象
public static Connection getConnect() throws Exception{
Connection con = null;
try {
con = dataSource.getConnection();
} catch (Exception e) {
throw e;
}
return con;
}
}
查询结果打印如下:
结语:通过以上对三种Java 中获取 mysql 连接方式的介绍,相信各位已经对此有了初步的了解,第一种很明显是硬编译的方法,就是把数据都写死,在之后的开发中更改起来会很麻烦;而第二种相对第一种方法来说要稍好一些,因为下次再使用时,我们直接修改 .properties 的配置文件就好了;而第三种我们使用了已经为我们写好的 DBCPUtils 包,直接省去了 Connection 对象,执行起来更简单,代码更简洁,资源利用率更低,到时候修改起来也方便,所以说,使用数据库连接池的方法相对来说更好一些。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。



