动态创建表

// 连接数据库
        String driver = myDataSourceEntity.getDriver();
        String url = myDataSourceEntity.getUrl();
        String user = myDataSourceEntity.getUser();
        String password = myDataSourceEntity.getPassword();
        try {
            Class.forName(driver);
            Connection conn = DriverManager.getConnection(url, user, password);
            if (!conn.isClosed()) {
                System.out.println("Succeeded connecting to the Database!");
                Statement statement = conn.createStatement();
                StringBuffer bufferSql = new StringBuffer();
                String[] tableName = templateId.split("-");
                String table = "";
                for (int i=0;i<tableName.length;i++){
                    table += tableName[i];
                }
                bufferSql.append("create table a"+ table +"("+"id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,");
                // 生成字段对应的字段名
                for (int i=0;i<li.length;i++){
                    bufferSql.append("a"+i+" varchar(255) DEFAULT NULL,");
                }
                // StringBuffer转为String  同时该sql后面带有“,”
                String haveDouHaoSql = bufferSql.toString();
                // 去掉末尾的逗号
                String noDouHaoSql = haveDouHaoSql.substring(0,haveDouHaoSql.length()-1);
                StringBuffer stringBuffer = new StringBuffer(noDouHaoSql);
                stringBuffer.append(")ENGINE=MyISAM DEFAULT CHARSET=utf8");
                String sql = stringBuffer.toString();
                statement.execute(sql);
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try{

            Workbook wb = null;
            InputStream is = null;

            File files = null;

            files = File.createTempFile("temp", null);
            file.transferTo(files);
            is = new FileInputStream(files);
            files.deleteOnExit();

            wb = Workbook.getWorkbook(is);

            int sheetSize = wb.getNumberOfSheets();
            Sheet sheet = wb.getSheet(0);
            int row_total = sheet.getRows();
            for (int j = 0; j < row_total; j++) {
                if(j == 0){
                    Cell[] cells = sheet.getRow(j);
                    System.out.println(cells[0].getContents());
                    System.out.println(cells[1].getContents());
                    System.out.println(cells[2].getContents());
                }
            }
        }catch (IOException e) {
            e.printStackTrace();
        } catch (BiffException e){
            e.printStackTrace();
        }

猜你喜欢

转载自blog.csdn.net/qq_37950196/article/details/108782157