首先创建mysql.properties文件
- #连接数据的url
- url = jdbc:mysql://localhost:3306/bjsxt?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
- #连接数据库的用户名
- username = root
- #连接数据库的密码
- userpwd = tcxtcx666
- #数据库的驱动
- driver = com.mysql.cj.jdbc.Driver
再创建Java
- /**
- * 优化数据库的连接
- */
- public class TestJdbc2 {
- public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
- //实例化Propreties对象
- Properties properties=new Properties();
- //读取properties文件的字节输入流对象
- InputStream is=TestJdbc2.class.getClassLoader().getResourceAsStream("mysql.properties");
- //读取properties文件并解析
- properties.load(is);
-
- //获取连接数据库的url
- final String url = properties.getProperty("url");
- //获取连接数据库的用户名
- final String username = properties.getProperty("username");
- //获取连接数据库的密码
- final String userpwd = properties.getProperty("userpwd");
-
- //获取加载数据库的驱动全名
- final String driver = properties.getProperty("driver");
-
- //加载注册驱动
- Class.forName(driver);
-
- //通过管理器对象获取连接对象
- Connection connection = DriverManager.getConnection(url,username,userpwd);
-
- System.out.println(connection);
- }