JDBC 入坑

晚上学习JDBC基础,做那种可灵活配置的代码,不用改代码,只需修改配置文件写了一个jdbc.properties里面的内容如下所示:

要配置Oracle数据库换成相应的配置内容即可

然后接下来就是坑了,在建立jdbc.properties的配置文件时,先是命名错了(后缀名propertities,大半夜都没看出来错),其次就是添加jdbc.properties的时候路径错了,下面是错误的目录结构

导致写Junit测试的时候不停的报出空指针异常,盯了好久都没有看到问题,然后突然就顿悟了,然后改了目录结构和文件后缀名,终于正常了。看来一定要细心啊,下图是正确的目录结构

附上源代码:

package com.jdbc.demo;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.util.Properties;

import org.junit.Test;

public class JDBCDemo01 {
/**
* 需要写一个公共方法,来读取公共文件,在不需要修改程序的情况下,只修改配置内容就可以
*
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws IOException
*/
public Connection getConnection() throws Exception {
// 定义相关变量
String driverClass = null;
String jdbcUrl = null;
String user = null;
String password = null;

// 读取配置文件
InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");

Properties properties = new Properties();
properties.load(in);
driverClass = properties.getProperty("driver");
jdbcUrl = properties.getProperty("jdbcUrl");
user = properties.getProperty("user");
password = properties.getProperty("password");

// 加载驱动
// Driver driver = (Driver) Class.forName(driverClass).newInstance();
Driver driver = (Driver) Class.forName(driverClass).newInstance();
// Class.forName(driverClass);

Properties info = new Properties();
info.put("user", "root");
info.put("password", "root");

// Connection connection = DriverManager.getConnection(jdbcUrl, user,
// password);
// 创建数据库连接对象

Connection connection = driver.connect(jdbcUrl, info);

return connection;
}

// 测试
@Test
public void testGetConnection() throws Exception {
System.out.println(getConnection());
}

}

Junit运行结果截图:

另外还留着一个问题:

Driver driver = (Driver) Class.forName(driverClass).newInstance();  这一行代码在IDE下没有强制类型转换成(Driver)的提示,自己加上也是不对

原文地址:https://www.cnblogs.com/yaoruozi/p/8491540.html