package com.platform.oracle;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.base.Custom4exception;
import com.base.CustomException;
import com.platform.utils.Configs;

public class OracleConnector {
	static {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			Configs.CONSOLE_LOGGER.info("Oracle驱动加载成功");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			new CustomException(Custom4exception.OracleSQL_Except, e);			
		}
	}

	public synchronized static Connection ConnectionBuilder(String url, String user,
			String password) {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			new CustomException(Custom4exception.OracleSQL_Except, e);
			Configs.CONSOLE_LOGGER.info("创建oracle连接失败: [" + e.getMessage() + "]");
		}
		return conn;
	}

	public synchronized static boolean canConnect(String url, String user, String password) {
		return (null != ConnectionBuilder(url, user, password));
	}

	public synchronized static ResultSet getSQLExecResultSet(Connection conn, String sql) {
		ResultSet resultSet = null;
		try {
			Statement statement = conn
					.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
							ResultSet.CONCUR_UPDATABLE);
			resultSet = statement.executeQuery(sql);
		} catch (SQLException e) {
			new CustomException(Custom4exception.OracleSQL_Except, e);
		}
		return resultSet;
	}

	public synchronized static ResultSet getSQLExecResultSet(String url, String user,
			String password, String sql) {
		return getSQLExecResultSet(ConnectionBuilder(url, user, password), sql);
	}

	/**
	 * 执行对oracle数据库的增、删
	 * 
	 * @param conn
	 * @param sql
	 * @return 是否执行成功
	 */
	public synchronized static boolean execOracleSQL(Connection conn, String sql) {
		boolean flag = false;
		try {
			Statement statement = conn.createStatement();
			statement.execute(sql);
			flag = true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			new CustomException(Custom4exception.OracleSQL_Except, e);			
		}
		return flag;
	}
	
	public synchronized static boolean execUpdateOracleSQL(Connection conn, String sql) {
		boolean flag = false;
		try {
			Statement statement = conn.createStatement();
			if(statement.executeUpdate(sql) > 0)
				flag = true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			new CustomException(Custom4exception.OracleSQL_Except, e, sql);			
		}
		return flag;
	}
}