java学习笔记:通过JDBC技术获取Oracle数据库连接

时间:2020-12-06 11:49:23

视频看了好几遍,终于有点思路了。总结一下使用java的JDBC技术连接数据库的方法。

本人使用额Oracle数据库,所以代码中只写Oracle数据库的连接方法。

java中提供了driver类,可以通过直接操作driver类来获取数据库的连接,同时,java中有一个DriverMabager类,我们可以通过使用DriverManager类获取数据库连接。


第一种方法:直接操作Driver来获取数据库连接:

1.我们要将连接数据库的信息放在一个jdbc.properties文件中,

2.读取路径下的properties文件,这里要用到输入流InputStream

3.创建一个Properties的对象,然后加载上面的对应的输入流

4.通过反射创建Driver对象

5.通过Driver的connect()方法获取数据库连接



/**
*编写一个通用的方法,在不修改源程序的情况下,可以获取任何数据库的连接
*解决方案:把数据库驱动Driver实现类的全类名,url,user,password
*放在一个配置文件中,通过配置文件的方式实现和具体的数据库相耦合
* @throws
* @throws IllegalAccessException
* @throws Exception
* */
public Connection getConnection() throws Exception{
String driverClass=null;
String user=null;
String jdbcUrl=null;
String password=null;

//读取路径下的jdbc.properties文件
InputStream in=
getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties=new Properties();
properties.load(in);
driverClass=properties.getProperty("driver");
user=properties.getProperty("user");
jdbcUrl=properties.getProperty("jdbcUrl");
password=properties.getProperty("password");
//通过反射创建Driver对象
Driver driver=
(Driver) Class.forName(driverClass).newInstance();

Properties info=new Properties();
info.put("user",user);
info.put("password",password);
//通过Driver的connect()方法获取数据库连接
Connection connection=driver.connect(jdbcUrl,info);

return connection;
}
@Test
public void testGetConnection() throws Exception{
System.out.println(getConnection());
}



第二种方法:通过DriverManager类获取数据库连接


1.准备连接数据库的四个字符串,在这个步骤中有以下四步:

(1)创建Properties的对象

(2)获取jdbc.properties的对应的输入流

(3)加载对应的输入流

(4)具体确定四个字符串

2.加载数据库驱动

3.通过DriverManager的getConnection()方法获取数据库连接


public void getConnection2() throws Exception{
//1.准备四个字符串
//1).创建Properties对象
Properties properties=new Properties();

//2).获取jdbc.properties文件对应的输入流
InputStream in=
this.getClass().getClassLoader().getResourceAsStream("jdbc.properties");

//3).加载2)对应的输入流
properties.load(in);

//4).具体确定四个字符串
String driver=properties.getProperty("driver");
String user=properties.getProperty("user");
String password=properties.getProperty("password");
String jdbcUrl=properties.getProperty("jdbcUrl");

//2.加载数据库驱动
Class.forName(driver);

//3.通过DriverManager的getConnection()方法获取数据库连接
System.out.println(DriverManager.getConnection(jdbcUrl,user,password));
}