1. 程式人生 > >Java使用JDBC連接數據庫

Java使用JDBC連接數據庫

sta 結果集 AD cti pac AC RM color 網上

不同數據庫需要去官網上面下載對應的驅動jar ,例如MySQL https://dev.mysql.com/downloads/connector/j/

  properties文件

 1 #MySQL
 2 mysqlDriver:com.mysql.jdbc.Driver
 3 mysqlUrl:jdbc\:mysql\://localhost\:3306\/test
 4 mysqlUser:root
 5 mysqlPassword:root
 6 
 7 #Oracle
 8 oracleDriver:oracle.jdbc.driver.OracleDriver
 9 oracleUrl:jdbc\:oracle\:thin@localhost\:1521\:orcl
10 oracleUser:username 11 oraclePassword:password
 1 package com.CommonUtil;
 2 
 3 /**
 4  * JDBC工具類
 5  * @author Andrew
 6  */
 7 
 8 import java.io.IOException;
 9 import java.sql.Connection;
10 import java.sql.DriverManager;
11 import java.sql.ResultSet;
12 import java.sql.SQLException;
13 import
java.sql.Statement; 14 import java.util.Properties; 15 16 public class JDBCUtil { 17 //可以幫助讀取和處理資源文件中的信息 18 private static Properties pros = null; 19 //靜態代碼塊,加載config.properties文件 20 static { 21 pros = new Properties(); 22 try { 23 pros.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("./com/config/config.properties"));
24 } catch (IOException e) { 25 e.printStackTrace(); 26 } 27 } 28 29 /** 30 * 建立MySQL數據庫連接 31 * @return java.sql.Connection連接對象 32 * @throws ClassNotFoundException 33 * @throws SQLException 34 */ 35 public static Connection getMySQLConn() throws ClassNotFoundException, SQLException { 36 Class.forName(pros.getProperty("mysqlDriver")); 37 return DriverManager.getConnection(pros.getProperty("mysqlUrl"), pros.getProperty("mysqlUser"), 38 pros.getProperty("mysqlPassword")); 39 } 40 41 /** 42 * 建立Oracle數據庫連接 43 * @return java.sql.Connection連接對象 44 * @throws ClassNotFoundException 45 * @throws SQLException 46 */ 47 public static Connection getOracleConn() throws ClassNotFoundException, SQLException { 48 Class.forName(pros.getProperty("oracleDriver")); 49 return DriverManager.getConnection(pros.getProperty("oracleUrl"), pros.getProperty("oracleUser"), 50 pros.getProperty("oraclePassword")); 51 } 52 53 /** 54 * 關閉所有的數據庫連接 55 * @param rs ResultSet對象 56 * @param stmt Statement對象 57 * @param conn Connection對象 58 * @throws SQLException 59 */ 60 public void closeAll(ResultSet rs, Statement stmt, Connection conn) throws SQLException { 61 if (rs != null) 62 rs.close(); 63 if (stmt != null) 64 stmt.close(); 65 if (conn != null) 66 conn.close(); 67 } 68 69 //關閉ResultSet結果集 70 public void close(ResultSet rs) throws SQLException { 71 if (rs != null) { 72 rs.close(); 73 } 74 } 75 76 //關閉Statement 77 public void close(Statement stmt) throws SQLException { 78 if (stmt != null) { 79 stmt.close(); 80 } 81 } 82 83 //關閉數據庫Connection連接對象 84 public void close(Connection conn) throws SQLException { 85 if (conn != null) { 86 conn.close(); 87 } 88 } 89 }

Java使用JDBC連接數據庫