package mobvista.dmp.util;

import java.sql.*;

/**
 * @package: mobvista.dmp.util
 * @author: wangjf
 * @date: 2019-06-13
 * @time: 19:43
 * @emial: jinfeng.wang@mobvista.com
 * @phone: 152-1062-7698
 */
public class JdbcUtils {
    private static final String USERNAME = "apptag_rw";
    //  private static final String USERNAME = "root";
    private static final String PASSWORD = "7gyLEVtkER3u8c9";
    //  private static final String PASSWORD = "19920627";
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql://dataplatform-app-tag.c5yzcdreb1xr.us-east-1.rds.amazonaws.com:3306";
    //  private static final String URL = "jdbc:mysql://localhost:3306";

    private Connection connection;
    private PreparedStatement pstmt;
    private ResultSet resultSet;

    /*
    public JdbcUtils() {
        try {
            System.out.println("数据库连接成功！");
        } catch (Exception e) {
        }
    }
    */

    /**
     * 获得数据库的连接
     *
     * @return
     */
    public Connection getConnection(String database) {
        try {
            connection = DriverManager.getConnection(URL + "/" + database + "?useUnicode=true&characterEncoding=utf8&useSSL=false", USERNAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 获得数据库的连接
     *
     * @return
     */
    public JdbcUtils() {
        try {
            Class.forName(DRIVER);
            String database = "dmp";
            connection = DriverManager.getConnection(URL + "/" + database + "?useUnicode=true&characterEncoding=utf8&useSSL=false", USERNAME, PASSWORD);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * query
     *
     * @param sql
     * @return
     * @throws SQLException
     */
    public ResultSet query(String sql) throws SQLException {
        pstmt = connection.prepareStatement(sql);
        ResultSet result = pstmt.executeQuery();
        return result;
    }

    /**
     * update
     *
     * @param sql
     * @return
     * @throws SQLException
     */
    public boolean replace(String sql) throws SQLException {
        pstmt = connection.prepareStatement(sql);
        return pstmt.execute();
    }

    /**
     * update
     *
     * @param sql
     * @return
     * @throws SQLException
     */
    public boolean update(String sql) throws SQLException {
        int result;
        pstmt = connection.prepareStatement(sql);
        result = pstmt.executeUpdate();
        boolean flag = result > 0;
        return flag;
    }


    /**
     * 释放数据库连接
     */
    public void releaseConn() {
        if (resultSet != null) {
            try {
                connection.close();
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}