栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Druid连接TIDB数据库生成表和插入值代码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Druid连接TIDB数据库生成表和插入值代码


@EqualsAndHashCode(callSuper = true)
@ConfigurationProperties(prefix = "datasource.tidb")
@Component
@Data
@Slf4j
public class TidbSource extends JDBCCacheSource {

    
    private static DataSource dataSource = null;

    
    private String database;

    
    private String driverClassName = "com.mysql.jdbc.Driver";

    private String getJdbcUrl() {
        return String.format("jdbc:mysql://%s:%s/%s?useUnicode=true&characterEncoding=UTF-8&useSSL=false&rewriteBatchedStatements=true&autoReconnect=true&failOverReadonly=false",
                this.host, this.port, this.database);
    }

    @PostConstruct
    public void init() {
        Properties properties = new Properties();
        properties.setProperty("url", this.getJdbcUrl());
        properties.setProperty("username", this.username);
        properties.setProperty("password", this.password);
        properties.setProperty("driverClassName", this.driverClassName);
        try {
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SqlExecuteException("tidb获得jdbc连接失败");
        }
    }

    
    @Override
    public Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new SqlExecuteException("tidb获得jdbc连接失败");
        }
    }


    
    @Override
    public void createTable(String tableName, List columns, String comment) {
        //获得创表语句
        String createTableSql = buildCreateTableSql(tableName, columns, comment);
        Connection connection = this.getConnection();
        
        Statement statement = null;
        //执行SQL
        try {
            statement = connection.createStatement();
            int count = statement.executeUpdate(createTableSql);
            log.info(String.format("tidb在%s创建表%s", DateTime.now().toDateStr(), tableName));
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new SqlExecuteException(String.format("tidb创建表%s失败", tableName));
        } finally {
            closeStatement(statement);
        }


    }

    
    @Override
    public void insertTable(String tableName, List columns, List> data) {
        if (CollectionUtil.isEmpty(data) || StrUtil.isBlank(tableName)) {
            return;
        }
        Connection connection = this.getConnection();
        PreparedStatement preparedStatement = null;
        try {
            //这里必须设置为false,我们手动批量提交
            connection.setAutoCommit(false);
            //SQL语句预处理,就是values(?,?,...,?),否则批处理不起作用
            preparedStatement = connection.prepareStatement(buildInsertPrepareSql(tableName, data));
            //插入数据
            for (Map columndata: data) {
                //获得字段
                List columnNames = new ArrayList<>(columnData.keySet());
                try {
                    for (int i = 0; i < columnNames.size(); i++) {
                        //获得当前字段的数据类型
                        int finalI = i;
                        Column phyColumn = columns.stream().filter(column -> column.getName().equals(columnNames.get(finalI))).collect(Collectors.toList()).get(0);
                        //赋值进入批序列
                        preparedStatementSetObject(preparedStatement, phyColumn, i, columnData.get(columnNames.get(i)));
                    }
                    //将要执行的SQL语句先添加进去,不执行
                    preparedStatement.addBatch();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new SqlExecuteException("批量插入数据出现错误");
                }
            }
            //执行插入
            preparedStatement.executeBatch();
            connection.commit();
            log.info(String.format("tidb %s 插入数据", tableName));
        } catch (SQLException e) {
            e.printStackTrace();
            throw new SqlExecuteException("批量插入数据出现错误");
        } finally {
            //关闭预处理
            closeStatement(preparedStatement);
            //关闭连接
            closeConnection(connection);
        }

    }

    
    private String buildCreateTableSql(String tableName, List columns, String comment) {
        StringBuilder createSql = new StringBuilder();
        createSql.append(String.format("CREATE TABLE IF NOT EXISTS `%s` (", tableName));
        //设置主键
        createSql.append(" `id` BIGINT UNSIGNED AUTO_INCREMENT, ");
        //拼接字段列表
        columns.forEach(column -> {
            createSql.append(String.format(" `%s` %s COMMENT '%s',", column.getName(), DBUtils.convertJavaTypeToDBType(column.getDataType()), column.getComment()));
        });
        //拼接主键及引擎信息
        createSql.append(String.format(" PRIMARY KEY (`id`) )ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='%s';", comment));
        return createSql.toString();
    }

    private String buildInsertPrepareSql(String tableName, List> data) {
        StringBuilder insertPrepareSql = new StringBuilder();
        insertPrepareSql.append(String.format("insert into %s (", tableName));
        //遍历字段
        Map columnData = data.get(0);
        //获得字段名
        Set columnSet = columnData.keySet();
        //拼接sql
        columnSet.forEach(column -> {
            insertPrepareSql.append(String.format("`%s`,", column));
        });
        //删除最后一个逗号
        insertPrepareSql.deleteCharAt(insertPrepareSql.length() - 1);
        //拼接SQL
        insertPrepareSql.append(") values (");
        //拼接问号
        columnSet.forEach(column -> {
            insertPrepareSql.append("?,");
        });
        //删除最后一个逗号
        insertPrepareSql.deleteCharAt(insertPrepareSql.length() - 1);
        insertPrepareSql.append(")");
        return insertPrepareSql.toString();
    }

    private void preparedStatementSetObject(PreparedStatement preparedStatement, Column column, Integer index, Object data) throws SQLException {
        index++;
        switch (column.getDataType()) {
            case "int":
            case "Integer":
                preparedStatement.setInt(index, Convert.toInt(data));
                break;
            case "long":
            case "Long":
                preparedStatement.setLong(index, Convert.toLong(data));
                break;
            case "bool":
            case "Boolean":
                preparedStatement.setBoolean(index, Convert.toBool(data));
                break;
            case "String":
            default:
                preparedStatement.setString(index, Convert.toStr(data));
                break;
        }
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/777385.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号