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


/**
 * @author daimao
 * @date 2022/3/15 5:57 下午
 */
@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连接失败");
        }
    }

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


    /**
     * 创建tidb表
     *
     * @param tableName 表名称
     * @param columns   列表
     * @param comment   注释
     */
    @Override
    public void createTable(String tableName, List<Column> columns, String comment) {
        //获得创表语句
        String createTableSql = buildCreateTableSql(tableName, columns, comment);
        Connection connection = this.getConnection();
        /**
         * 扩大对象的使用范围,防止在catch处关闭资源爆红
         */
        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);
        }


    }

    /**
     * 将数据插入表中
     *
     * @param tableName 表名
     * @param columns   字段
     * @param data      数据
     */
    @Override
    public void insertTable(String tableName, List<Column> columns, List<Map<String, Object>> 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<String, Object> columnData : data) {
                //获得字段
                List<String> 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);
        }

    }

    /**
     * 创建tidb表
     *
     * @param tableName 表名称
     * @param columns   列表
     * @param comment   注释
     */
    private String buildCreateTableSql(String tableName, List<Column> 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<Map<String, Object>> data) {
        StringBuilder insertPrepareSql = new StringBuilder();
        insertPrepareSql.append(String.format("insert into %s (", tableName));
        //遍历字段
        Map<String, Object> columnData = data.get(0);
        //获得字段名
        Set<String> 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;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Druid连接池是一个高效、可靠的数据库连接池。它支持多种数据库,包括MySQL。使用Druid连接池可以大大提高应用程序的数据库访问性能。 要使用Druid连接连接MySQL数据库,需要在项目中引入Druid和MySQL的依赖包。然后,在配置文件中配置Druid连接池的相关参数,包括数据库连接URL、用户名、密码、驱动类等。具体的配置方式可以参考Druid官方文档。 下面是一个简单的配置示例: ``` # 数据库连接池配置 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver # 连接池配置 spring.datasource.druid.initial-size=5 spring.datasource.druid.min-idle=5 spring.datasource.druid.max-active=20 spring.datasource.druid.max-wait=60000 spring.datasource.druid.time-between-eviction-runs-millis=60000 spring.datasource.druid.min-evictable-idle-time-millis=300000 spring.datasource.druid.validation-query=SELECT 1 FROM DUAL spring.datasource.druid.test-while-idle=true spring.datasource.druid.test-on-borrow=false spring.datasource.druid.test-on-return=false spring.datasource.druid.pool-prepared-statements=true spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20 spring.datasource.druid.filters=stat,wall,log4j spring.datasource.druid.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 ``` 配置好之后,就可以在代码中通过Druid连接池获取数据库连接,并执行SQL语句了。例如: ``` // 获取数据库连接 Connection conn = dataSource.getConnection(); // 执行SQL语句 Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM user"); while (rs.next()) { System.out.println(rs.getString("name")); } // 关闭连接 rs.close(); stmt.close(); conn.close(); ``` 需要注意的是,使用完数据库连接后一定要及时关闭连接,释放资源,否则会造成连接泄漏和系统资源浪费。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值