jdbc加载驱动、连接数据库(oracle) 作者:马育民 • 2020-11-11 15:09 • 阅读:10076 # 介绍 以mysql为例,加载驱动器、注册驱动 # 加载驱动 ``` Class c=Class.forName("oracle.jdbc.driver.OracleDriver"); ``` # 注册驱动 ``` Driver driver=(Driver)c.newInstance(); DriverManager.registerDriver(driver); ``` ### 可省略注册驱动 查看mysql的驱动类`oracle.jdbc.driver.OracleDriver`,发现已经实现了注册,所以不需要注册 ``` public class Driver extends NonRegisteringDriver implements java.sql.Driver { public Driver() throws SQLException { } static { try { DriverManager.registerDriver(new Driver()); } catch (SQLException var1) { throw new RuntimeException("Can't register driver!"); } } } ``` # 连接数据库 ``` String driver="oracle.jdbc.driver.OracleDriver"; String url="jdbc:oracle:thin:@localhost:1521:douban"; String username="scott"; String password="tiger"; //加载驱动 Class.forName(driver); //创建数据库连接 Connection conn=DriverManager.getConnection(url, username, password); if(conn!=null && !conn.isClosed()){ System.out.println("连接成功!"); } ``` ### 将数据库信息写在配置文件中 数据库ip、port、库名、用户名、密码可能会发生变化,写死在代码中不合理,所以要写在配置文件中 创建文件 `db.properties` ,内容如下: 适合mysql8 ``` driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/book?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT user=root password=123456 ``` ### 读取配置文件 ``` FileInputStream fis = new FileInputStream(filename); Properties p = new Properties(); p.load(fis); String url = p.getProperty("url"); String user = p.getProperty("user"); String password = p.getProperty("password"); String driver = p.getProperty("driver"); ``` 原文出处:http://malaoshi.top/show_1IX1OVnrWtG.html