package com.jay.monitor.data.server.utils;

import com.alibaba.druid.util.JdbcUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.sql.Connection;

/**
 * @Module TODO
 * @Description TODO
 * @Author liukaixiong
 * @Date 2020/11/5 11:38
 */
public class SqlUtils {

    private static Logger logger = LoggerFactory.getLogger(SqlUtils.class);

    /**
     * 创建表
     *
     * @param connection    数据库连接
     * @param tableName     要创建的表名
     * @param likeTableName 复制的表名
     */
    public static void createTable(Connection connection, String tableName, String likeTableName) {
        Assert.notNull(connection, "数据库连接不能为空");
        Assert.notNull(tableName, "表名不能为空");
        Assert.notNull(likeTableName, "表名不能为空");
        try {
            String sql = "create table " + tableName + " like " + likeTableName;
            JdbcUtils.execute(connection, sql);
        } catch (Exception e) {
            if (e.getMessage().indexOf("already exists") > 0) {
                logger.warn("表 " + tableName + " 已经创建!");
            } else {
                logger.error("创建表失败 : " + e.getMessage());
            }
        }
    }

}
