package com.template.util;

import org.springframework.beans.factory.annotation.Autowired;

import java.sql.*;

/**
 * @Author：liuxinyue
 * @Package：com.template.util
 * @Project：cloud-server
 * @name：ToIoTDBTest
 * @Date：2024/9/24 10:12
 */
public class ToIoTDBTest {

    private static final String host = "47.116.173.119";
    private static final String url = "jdbc:iotdb://" + host + ":6667/";
    private static final String username = "root";
    private static final String password = "root";


    public static void main(String[] args) throws SQLException, ClassNotFoundException {

        ToIoTDB toIoTDB = new ToIoTDB();
        Connection connection = toIoTDB.getConnection();
//      Connection connection = (Connection) new IOTdbJDBCUtils(url, username, password).getConnection();
        System.out.println(connection!=null?"打开连接成功！":"打开连接失败！");

        ResultSet rs=null;
        String storgeGroup="root.test";
        Statement statement = connection.createStatement();
        String sql=String.format("set storage group to %s",storgeGroup);
        statement = connection.createStatement();
        int i = statement.executeUpdate(sql);
        System.out.println("当前创建组的结果为:"+i);

        //查看创建的组是否存在
        sql="SHOW STORAGE GROUPS"; //查看所有的存储组
        rs= statement.executeQuery(sql);
        outputResult(rs);

        sql=String.format("show storage group  %s",storgeGroup);
        rs=statement.executeQuery(sql);
        outputResult(rs);
        //统计存在的数量
        sql=String.format("count storage group %s",storgeGroup);
        rs=statement.executeQuery(sql);
        outputResult(rs);
    }

    private static void outputResult(ResultSet resultSet) throws SQLException {
        if (resultSet != null) {
            System.out.println("--------------------------");
            final ResultSetMetaData metaData = resultSet.getMetaData();
            final int columnCount = metaData.getColumnCount();
            for (int i = 0; i < columnCount; i++) {
                System.out.print(metaData.getColumnLabel(i + 1) + ", ");
            }
            System.out.println();
            while (resultSet.next()) {
                for (int i = 1;; i++) {
                    System.out.print(resultSet.getString(i));
                    if (i < columnCount) {
                        System.out.print(", ");
                    } else {
                        System.out.println();
                        break;
                    }
                }
            }
            System.out.println("--------------------------\n");
        }
    }


}
