package com.icool.common.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;
/**
*
* @author ZH_Q
* @version 1.0
*/
public class GetConn {
private Connection conn=null;
private String usName;
private String usPwd;
private String Clfn;
private String dmName;
//調用空參構造,默認啟用本地數據庫
public GetConn() {
this.Clfn ="oracle.jdbc.driver.OracleDriver";
this.dmName ="jdbc:oracle:thin:@localhost:1521:orcl";
this.usPwd = "q792002998";
this.usName = "system";
}
/**
* @return 數據庫連接對象
*/
public Connection getConn() {
try
{
Class.forName(Clfn);
conn = DriverManager.getConnection(dmName,usName,usPwd);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* @return 根據SQL語句查詢出的結果集
* @throws SQLException
*/
public ResultSet executeQuery(String sql) throws SQLException {
conn =getConn();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
return rs;
}
/**
* @return 影響數據行數
* @throws SQLException
*/
public int executeUpdate(String sql) throws SQLException {
Statement stmt = null;
int i = 0;
getConn();
stmt = conn.createStatement();
i = stmt.executeUpdate(sql);
return i;
}
/**
* @return 根據SQL語句返回預編譯對象
* @throws SQLException
*/
public PreparedStatement PreparedStatement(String sql) throws SQLException {
PreparedStatement pstmt = null;
getConn();
pstmt= conn.prepareStatement(sql);
return pstmt;
}
/**
* @param 關閉數據庫連接
* @throws DataBaseExpection
*/
public void close(){
if(conn!=null) {
try
{
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* @param 設置是否自動提交
* @throws SQLException
*/
public void setAutoCommit(boolean b) throws SQLException {
getConn();
conn.setAutoCommit(b);
}
public void commit() throws SQLException {
getConn();
conn.commit();
}
public void rollback() throws SQLException {
getConn();
conn.rollback();
}
}