- package com.jwgl.util;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- /**
- * 封裝Oracle數據庫常用操作
- *
- * @author 劉鵬
- *
- */
- public class DbUtil {
- /**
- * 取得Connection
- *
- * @return
- */
- public static final String DBDRIVER="oracle.jdbc.driver.OracleDriver";
- public static final String DBURL="jdbc:oracle:thin:@127.0.0.1:1521:orcl";
- public static final String DBUSER="kong";
- public static final String DBPASS="kong";
- public static Connection conn = null;
- public static Statement pstm = null;
- public static PreparedStatement pstmt = null;
- public static ResultSet rs = null;
- /**
- * 取得數據庫連接
- * @return
- */
- public static Connection getConnection(){
- try{
- Class.forName(DBDRIVER);
- }catch(ClassNotFoundException e){
- e.printStackTrace();
- }
- try{
- conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
- }catch(SQLException e){
- e.printStackTrace();
- }
- return conn;
- }
- /**
- * 數據庫操作Statement
- * @return
- */
- public static Statement getStatement(Connection con){
- //con = DbUtil.getConnection();
- try {
- if (con != null) {
- pstm = con.createStatement();
- }
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return pstm;
- }
- /**
- * 數據庫操作PreparedStatement
- * @return
- */
- public static PreparedStatement getPreparedStatement(Connection con,String sql) {
- //con = DbUtil.getConnection();
- if (con != null) {
- try {
- pstmt = conn.prepareStatement(sql);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- return pstmt;
- }
- /* 此方法不需要寫,會出現丟失In或者Out參數
- public static ResultSet getResultSet(Connection conn,String sql){
- pstmt = DbUtil.getPreparedStatement(conn, sql);
- try {
- rs = pstmt.executeQuery();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return rs;
- }
- */
- /**
- * 關閉數據庫連接
- * @param conn
- */
- public static void close(Connection conn){
- if(conn!=null){
- try{
- conn.close();
- }catch(SQLException e){
- e.printStackTrace();
- }
- }
- }
- /**
- * 關閉數據庫操作Statement
- * @param stmt
- */
- public static void close(Statement stmt){
- if(stmt!=null){
- try{
- stmt.close();
- }catch(SQLException e){
- e.printStackTrace();
- }
- }
- }
- /**
- * 關閉數據庫操作PreparedStatement
- * @param pstmt
- */
- public static void close(PreparedStatement pstmt){
- if(pstmt!=null){
- try{
- pstmt.close();
- }catch(SQLException e){
- e.printStackTrace();
- }
- }
- }
- /**
- * 關閉數據庫查詢
- * @param rs
- */
- public static void close(ResultSet rs){
- if(rs!=null){
- try{
- rs.close();
- }catch(SQLException e){
- e.printStackTrace();
- }
- }
- }
- /**
- * 主方法用於測試
- * @param args
- */
- public static void main(String[] args) {
- System.out.println(DbUtil.getConnection());
- }
- }
Oracle連接數據庫封裝類
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.