1. 程式人生 > >工作總結之----java程式碼連線資料庫(SqlServer和oracle)

工作總結之----java程式碼連線資料庫(SqlServer和oracle)

程式碼:

import java.sql.*;
public class JDBCUtil {
    private static final String DBDRIVERSQLSWRVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";// sqlserver驅動類類名
private static final String DBDRIVERORACLE = "oracle.jdbc.driver.OracleDriver";// oracle驅動類類名
private static final String DBNAME = "xxxx";// 資料庫名
private static final String DBUSER = "xxxx";// 資料庫使用者名稱private static final String DBPASSWORD = "xxxxx";// 資料庫密碼 private static final String DBURL = "jdbc:sqlserver://IP:prot;DatabaseName="+DBNAME;// 連線URL private static final String DBUSERORCL = "xxxx";// oracle資料庫使用者名稱 private static final String DBPASSWORDORCL
= "xxxx";// oracle資料庫密碼 private static final String DBURLORCL = "jdbc:oracle:thin:@IP:prot:資料庫名";// oracle連線URL private static Connection conn = null; private static PreparedStatement ps = null; private static ResultSet rs = null; /* * 獲取資料庫連線 */ public static Connection getConnection() { try
{ Class.forName(DBDRIVERSQLSWRVER);// 註冊驅動 System.out.println("成功載入SQL Server驅動程式"); conn = DriverManager.getConnection(DBURL,DBUSER, DBPASSWORD);// 獲得連線物件 System.out.println("資料庫連線成功"); } catch (ClassNotFoundException e) {// 捕獲驅動類無法找到異常 System.out.println("找不到SQL Server驅動程式"); System.out.println(e.toString()); e.printStackTrace(); } catch (SQLException e) {// 捕獲SQL異常 e.printStackTrace(); } return conn; } public static Connection getConnectionOracle() { try { Class.forName(DBDRIVERORACLE);// 註冊驅動 System.out.println("成功載入SQL Server驅動程式"); conn = DriverManager.getConnection(DBURLORCL,DBUSERORCL, DBPASSWORDORCL);// 獲得連線物件 System.out.println("資料庫連線成功"); } catch (ClassNotFoundException e) {// 捕獲驅動類無法找到異常 System.out.println("找不到oracle驅動程式"); System.out.println(e.toString()); e.printStackTrace(); } catch (SQLException e) {// 捕獲SQL異常 e.printStackTrace(); } return conn; } public static void closeAll(Connection conn, Statement stmt,PreparedStatement pstmt, ResultSet rs) { try { if (rs != null) { rs.close(); } if (pstmt != null) { pstmt.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } System.out.print("關閉成功"); }catch (SQLException e){ System.out.print("關閉失敗"); } } public static final void main(String[] args) throws SQLException { Connection conn = getConnection(); conn.close(); } }