Java SQL Table Create createTable(Connection conn, String sqlText)

Here you can find the source of createTable(Connection conn, String sqlText)

Description

create Table

License

Apache License

Declaration

protected static String createTable(Connection conn, String sqlText) throws SQLException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.sql.Connection;

import java.sql.SQLException;
import java.sql.Statement;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static final String TMP_TABLE_PREFIX = "tmp_";

    protected static String createTable(Connection conn, String sqlText) throws SQLException {
        String tableName = parseSelectTableName(sqlText);
        if (tableName.length() == 0) {
            return "";
        }/*from w w  w  . ja  va  2 s. co m*/
        tableName = TMP_TABLE_PREFIX + tableName + System.currentTimeMillis();
        String sql = "CREATE TABLE " + tableName + " AS SELECT * FROM (" + sqlText + ") t LIMIT 0";
        String dropSql = "DROP TABLE IF EXISTS " + tableName;
        Statement stmt = null;
        try {
            stmt = conn.createStatement();
            stmt.executeUpdate(dropSql);
            stmt.executeUpdate(sql);
        } finally {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                }
            }
        }
        return tableName;
    }

    public static String parseSelectTableName(String sql) {
        sql = sql.replaceAll("\n", " ");
        Pattern p = Pattern.compile("(?i)(?<=(?:from)\\s{1,1000})(\\w+)");
        Matcher m = p.matcher(sql);
        if (m.find()) {
            return m.group();
        }
        return "";
    }
}

Related

  1. createTable(Connection conn, String createTableStatement)
  2. createTable(Connection conn, String inputSqlType, String sortOrder)
  3. createTable(Connection connection)
  4. createTable(Connection dbConn, String tableName, String columnSpec)
  5. createTable(String query)
  6. createTableAndLoadData(Statement stmt, String tableName)