package com.shr.utils;

import java.sql.*;

import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;


/**
 * 直接访问数据库
 * @author Administrator
 *
 */
public class DBHelper {

	private static DBHelper dbHelper=null;
	private String jdbcConnectionStr;
	private Connection connection;
	private DataSourceProperties dataSource;
	private PreparedStatement preparedStatement;
	private ResultSet resultSet;
	
	private DBHelper() {
		jdbcConnectionStr = dataSource.getUrl();	
	}
	
	public static DBHelper createDBHelper(DataSourceProperties dataSource) {
	
		dbHelper = new DBHelper();
		dbHelper.dataSource = dataSource;
		dbHelper.initDB();
		return dbHelper;
	}
	
	public void getConn() {
	
		try {
			connection = DriverManager.getConnection(jdbcConnectionStr, dataSource.getUsername(), dataSource.getPassword());
			connection.setAutoCommit(false);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	
	}
	
	public void close() {
	
		if (resultSet != null) {
			try {
				resultSet.close();
				if (preparedStatement != null) {
					preparedStatement.close();
				}
				if (connection != null) {
					connection.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	
	}
	
	public ResultSet executeQuery(String sql, Object[] params) {
		dbHelper.setPrepareStatementParams(sql, params);
		try {
			resultSet = preparedStatement.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return resultSet;
	}
	
	public Boolean executeUpdate(String sql, Object[] params) {
	
		boolean result = false;
		dbHelper.setPrepareStatementParams(sql, params);
		try {
			if (preparedStatement.executeUpdate() > 0) {
				dbHelper.commit();
				result = true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return result;
	
	}
	
	@SuppressWarnings("unused")
	private void setPrepareStatementParams(String sql, Object[] params) {
	
		try {
			preparedStatement = connection.prepareStatement(sql);
			if (params != null) {
				for (int i = 0; i < params.length; i++) {
					preparedStatement.setObject((i + 1), params[i]);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	
	}
	
	private void initDB() {
		try {
			Class.forName(dataSource.getDriverClassName());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	private void commit() {
	
		try {
			connection.commit();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}