標籤:
/**
* 通過改變更配置置檔案來串連不同資料庫
*/
package com.xykj.jdbc;import static org.junit.Assert.*;import java.io.InputStream;import java.sql.Connection;import java.sql.Driver;import java.util.Properties;import org.junit.Test;public class JDBCTest0 { 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(); Properties info = new Properties(); info.put("user",user); info.put("password", password); Connection connection = driver.connect(jdbcUrl, info); return connection; } @Test public void testGetConnection() throws Exception{ System.out.println(getConnection()); }}
/*** jdbc串連oracle資料庫**/
1 package com.xykj.jdbc; 2 3 import static org.junit.Assert.*; 4 import java.sql.*; 5 import java.util.Properties; 6 7 import org.junit.Test; 8 9 public class JDBCTest {10 11 /**12 * Driver是一個介面:資料庫廠商必須提供實現的介面,能從其中擷取資料庫連接。13 * 1.加入oracle驅動14 * 1>建立lib目錄,複製粘貼jar包放入lib。15 * 2>右鍵jar包,build path,add 加入到類路徑下。16 */17 @Test18 public void testDriver() {19 ResultSet res=null; //建立一個結果集對象20 PreparedStatement pre = null; //建立先行編譯語句對象,一般都是用這個而不用Statement21 Connection connection = null; //建立一個資料庫連接22 try23 {24 25 //1.建立一個Driver實作類別的對象26 Driver driver = new oracle.jdbc.driver.OracleDriver(); //載入Oracle驅動程式27 28 //2.準備串連資料庫的基本資料:url,user,password29 String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";30 Properties info = new Properties();31 info.put("user", "system");32 info.put("password", "sys");33 34 //3.調用Driver介面的connect(url,info)擷取資料庫連接35 connection = driver.connect(url, info); //擷取串連36 System.out.println(connection);37 System.out.println("資料庫連接成功!");38 39 //4.對資料庫進行操作40 String sql = "select * from Stu where Name = ?"; //先行編譯語句,?代表參數41 pre = connection.prepareStatement(sql); //執行個體化先行編譯語句 42 pre.setString(1, "張三"); // 設定參數,前面的1表示參數的索引,而不是表中列名的索引43 res = pre.executeQuery(); //執行查詢44 while(res.next())45 46 System.out.println("姓名:"+res.getString("name") 47 + "性別:"+res.getString("sex") 48 + "年齡:"+res.getString("age"));49 }50 catch (Exception e )51 {52 e.printStackTrace();53 }54 finally55 {56 try57 {58 // 逐一將上面的幾個對象關閉,因為不關閉的話會影響效能、並且佔用資源59 // 注意關閉的順序,最後使用的最先關閉60 if(res != null)61 res.close();62 if(pre != null)63 pre.close();64 if(connection != null)65 connection.close();66 System.out.println("資料庫連接已關閉!");67 }68 catch(Exception e){69 e.printStackTrace();70 }71 }72 }73 }
jdbc串連oracle資料庫