【JDBC】Extra01 Oracle-JDBC
关于驱动包依赖:
官网提供的地址:
https://www.oracle.com/database/technologies/jdbc-drivers-12c-downloads.html
Maven仓库提供的:
https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc8
看不懂版本命名规则,介绍信息中只有简单的几句兼容JDK版本就没有了。。。
先试试这个版本的:
<!-- https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc8 --> <dependency> <groupId>com.oracle.database.jdbc</groupId> <artifactId>ojdbc8</artifactId> <version>19.7.0.0</version> <scope>test</scope> </dependency>
测试类编写:
@Test public void connectorTest() throws Exception{ Class.forName("oracle.jdbc.driver.OracleDriver"); // final String URL = "jdbc:oracle:thin:@127.0.0.1:1521:orcl"; final String URL2 = "jdbc:oracle:thin:@//127.0.0.1:1521/orcl"; final String USERNAME = "system"; final String PASSWORD = "123456"; Connection connection = DriverManager.getConnection(URL2, USERNAME, PASSWORD); System.out.println(connection); connection.close(); }
发现也很简单,注册驱动包路径之后剩下的东西也是一样操作的
就是发现两个URL链接地址都是可以使用的。。。。
打印输出链接对象
oracle.jdbc.driver.T4CConnection@14bf9759
Process finished with exit code 0
连接参数解耦剥离:
【ojdbc.properties】
oracle.jdbc.DriverClass = oracle.jdbc.driver.OracleDriver
oracle.jdbc.Url = jdbc:oracle:thin:@//127.0.0.1:1521/orcl
oracle.jdbc.Username = system
oracle.jdbc.Password = 123456
链接工具类:
package cn.zeal4j.util; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; /** * @author Administrator * @file Oracle-JDBC * @create 2020 09 27 11:59 */ public class OJdbcUtil { private OJdbcUtil() {} private static String driverClassName; private static String connectUrl; private static String username; private static String password; static { try { InputStream resourceAsStream = OJdbcUtil.class.getClassLoader().getResourceAsStream("ojdbc.properties"); Properties properties = new Properties(); properties.load(resourceAsStream); driverClassName = properties.getProperty("oracle.jdbc.DriverClass"); connectUrl = properties.getProperty("oracle.jdbc.Url"); username = properties.getProperty("oracle.jdbc.Username"); password = properties.getProperty("oracle.jdbc.Password"); Class.forName(driverClassName); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConnection() { try { return DriverManager.getConnection(connectUrl, username, password); } catch (SQLException throwables) { throwables.printStackTrace(); } return null; } }
测试类:
@Test public void connectorTest2() throws Exception{ Connection connection = OJdbcUtil.getConnection(); System.out.println(connection); connection.close(); }
测试结果:
oracle.jdbc.driver.T4CConnection@553f17c Process finished with exit code 0