package com.mobvista.apptag.utils;

import java.sql.*;

/**
 * @package: com.mobvista.apptag.utils
 * @author: wangjf
 * @date: 2019-09-04
 * @time: 16:19
 * @email: jinfeng.wang@mobvista.com
 * @phone: 152-1062-7698
 */
public class GetPreviewUrl {
    void get() throws SQLException {
        Connection connection = DriverManager.getConnection(
                "jdbc:mysql://adn-data-foronlinetest.c5yzcdreb1xr.us-east-1.rds.amazonaws.com:3306/mob_adn?useUnicode=true&characterEncoding=utf8&useSSL=false", "adnro", "YcM123glh");
        String querySql = "select md5(preview_url) url_md5,b.preview_url preview_url from campaign_list_cpi a join campaign_list b on a.campaign_id = b.id where is_ec_adv = 1 group by b.preview_url";
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(querySql);
            ResultSet resultSet = preparedStatement.executeQuery();
            insert(resultSet);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
        }
    }

    void insert(ResultSet resultSet) throws SQLException {

        Connection con = DriverManager.getConnection(
                "jdbc:mysql://dataplatform-app-tag.c5yzcdreb1xr.us-east-1.rds.amazonaws.com:3306/app_tag?useUnicode=true&characterEncoding=utf8&useSSL=false", "apptag_rw", "7gyLEVtkER3u8c9");

        String insertSql = "INSERT INTO ec_tag_list(url_md5, preview_url) VALUES @VALUES ON DUPLICATE KEY UPDATE tag = tag";
        StringBuilder stringBuilder = new StringBuilder();
        while (resultSet.next()) {
            String urlMd5 = resultSet.getString("url_md5");
            String previewUrl = resultSet.getString("preview_url");
            stringBuilder.append("('").append(urlMd5).append("','").append(previewUrl).append("'),");
        }
        PreparedStatement stmt = con.prepareStatement(insertSql.replace("@VALUES", stringBuilder.substring(0, stringBuilder.length() - 1)));
        stmt.execute();
        con.close();
    }

    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        GetPreviewUrl getPreviewUrl = new GetPreviewUrl();
        getPreviewUrl.get();
    }
}
