java程序有连接数据库_Java程序连接数据库
/**
* 了解: 利用 Driver 接口的 connect 方法獲取連接
*/
// 第一種實現
/**
* 了解: 利用 Driver 接口的 connect 方法獲取連接
*/
@Test
public void oracleJdbcTest() throws Exception {
Driver driver = null; // sun提供的接口
String url = "jdbc:oracle:thin:@192.168.5.139:1521:ORCL";
Properties info = null;
info = new Properties();
info.put("user", "scott");
info.put("password", "tiger");
driver = new OracleDriver(); // Oracle數據庫廠商自己實現sun提供的接口Driver
Connection connect = driver.connect(url, info); // 獲取連接
System.out.println(connect);
}
======================================
/**
* 了解: 使用 DriverManager 來獲取數據庫連接
* 版本1:
* 好處: 不需要使用原生的 Driver 方法來獲取連接.
* 缺點: 還是耦合了具體的實現類.
*/
//第二種實現
@Test
public void oracleJdbcTest1() throws Exception{
Connection connection=null;
DriverManager.registerDriver(new OracleDriver()); //驅動管理器注冊Oracle驅動,實現Java程序可以連接Oracle數據庫,如果想要連接不同的數據庫則需要注冊不同的數據庫驅動
String url="jdbc:oracle:thin:@192.168.5.139:1521:ORCL";
Properties info=null;
info=new Properties();
info.put("user", "scott");
info.put("password", "tiger");
connection=DriverManager.getConnection( url, info) ; //DriverManager驅動管理器類,里面的方法都是靜態(tài)的,類調用獲取到一個連接
System.out.println(connection);
}
====================================
/**
* 了解: 更進一步, 不需要關聯任何 JDBC 驅動的實現類。
* 但需要提供 JDBC 驅動中 Driver 接口的實現類的全類名的字符串.
*/
//第三種實現
@Test
public void oracleJdbcTest2() throws Exception, InstantiationException, IllegalAccessException, ClassNotFoundException{
Connection connection=null;
String className="oracle.jdbc.driver.OracleDriver";
DriverManager.registerDriver((Driver)Class.forName(className).newInstance()); //注冊驅動
String url="jdbc:oracle:thin:@192.168.5.139:1521:ORCL";
Properties info=null;
info=new Properties();
info.put("user", "scott");
info.put("password", "tiger");
connection=DriverManager.getConnection(url,info);
System.out.println(connection);
}
===========================================================
/**
* 能創(chuàng)建一個不和具體 Driver 耦合的獲取數據庫連接的方法. 即在方法中不再關聯任何數據庫驅動的 JDBC 實現.
*@throws SQLException
*/
/**
* final version: 若需要手動獲取數據庫連接:
*
* 更進一步, 不需要關聯任何 JDBC 驅動的實現類。
* 但需要提供 JDBC 驅動中 Driver 接口的實現類的全類名的字符串.
*
* 實際上, 在驅動的實現類中有一個靜態(tài)代碼塊: 創(chuàng)建了 Driver 實現類的對象, 并把其注冊給 DriverManager
* static {
* try {
* java.sql.DriverManager.registerDriver(new Driver());
* } catch (SQLException E) {
* throw new RuntimeException("Can't register driver!");
* }
* }
*
* 而調用 Class 的 forName 方法在加載類實例時, 會調用靜態(tài)代碼塊.
*
*/
//第四種實現(最常用)
@Test
public void oracleJdbcTest3() throws Exception{
Connection connection=null;
String className="oracle.jdbc.driver.OracleDriver";
String url="jdbc:oracle:thin:@192.168.5.139:1521:ORCL";
Properties info=null;
info=new Properties();
info.put("user", "scott");
info.put("password", "tiger");
Class.forName(className).newInstance();//加載驅動
connection=DriverManager.getConnection(url,info);
System.out.println(connection);
}
總結
以上是生活随笔為你收集整理的java程序有连接数据库_Java程序连接数据库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 辽宁师范大学java_辽宁师范大学心理学
- 下一篇: java reduce.mdn_redu