查看“获取数据库连接的方式五”的源代码
←
获取数据库连接的方式五
跳到导航
跳到搜索
因为以下原因,您没有权限编辑本页:
您所请求的操作仅限于该用户组的用户使用:
用户
您可以查看和复制此页面的源代码。
https://www.bilibili.com/video/BV1eJ411c7rf?p=11 将连接数据库要用到的基本信息外部化到配置文件中,通过读取配置文件的方式获取连接 外部化的配置文件:resources\jdbc.properties<syntaxhighlight lang="properties"> user=root password=123456 url=jdbc:mysql://localhost:3306/guns driverClass=com.mysql.cj.jdbc.Driver </syntaxhighlight> <syntaxhighlight lang="java"> import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class ConnectionTest5 { @Test public void testConnection() throws SQLException, ClassNotFoundException, IOException { //1.读取配置文件中的4个基本信息 InputStream is = ConnectionTest5.class.getClassLoader().getResourceAsStream("jdbc.properties"); Properties pros = new Properties(); pros.load(is); String user = pros.getProperty("user"); String password = pros.getProperty("password"); String url = pros.getProperty("url"); String driverClass = pros.getProperty("driverClass"); System.out.println(user); System.out.println(password); System.out.println(url); System.out.println(driverClass); //2.加载驱动 Class.forName(driverClass); //3.获取连接 Connection conn = DriverManager.getConnection(url, user, password); System.out.println(conn); } } </syntaxhighlight><syntaxhighlight lang="console"> root 123456 jdbc:mysql://localhost:3306/guns com.mysql.cj.jdbc.Driver com.mysql.cj.jdbc.ConnectionImpl@147ed70f </syntaxhighlight>这种方案的好处是解耦了配置参数与业务逻辑实现
返回至
获取数据库连接的方式五
。
导航菜单
个人工具
登录
名字空间
页面
讨论
变种
视图
阅读
查看源代码
查看历史
更多
搜索
导航
首页
Spring Boot 2 零基础入门
Spring Cloud
Spring Boot
设计模式之禅
VUE
Vuex
Maven
算法
技能树
Wireshark
IntelliJ IDEA
ElasticSearch
VirtualBox
软考
正则表达式
程序员精讲
软件设计师精讲
初级程序员 历年真题
C
SQL
Java
FFmpeg
Redis
Kafka
MySQL
Spring
Docker
JMeter
Apache
Linux
Windows
Git
ZooKeeper
设计模式
Python
MyBatis
软件
数学
PHP
IntelliJ IDEA
CS基础知识
网络
项目
未分类
MediaWiki
镜像
问题
健身
国债
英语
烹饪
常见术语
MediaWiki帮助
工具
链入页面
相关更改
特殊页面
页面信息