这是一些未知数据库载体的本地创建语句

String createStatement = "CREATE TABLE test_database.test_table " +
"AS  " +
"(  " +
"var1,  " +
"var2  " +
")  " +
";  "
);


我需要解析此字符串test_database.test_table

我事先不知道该CREATE语句是什么SQL风格。如果我知道的话,我只会使用类似

String table = createStatement.split(" ")[2];


但是上述解决方案可能不适用于所有数据库。如果某些数据库在表名中允许空白怎么办?所以我必须使用Hibernate。

怎么样?

最佳答案

我认为Hibernate不能处理所有情况,尤其是在处理诸如Transact-SQL或CREATE GLOBAL TEMPORARY TABLE甚至CREATE TEMPORARY TABLESPACE之类的东西时,然后在使用AS,AS SELECT甚至PARALLEL COMPRESS AS SELECT之后,要考虑的表名。

但是,您也可以选择一种方法,该方法可以从提供的CREATE TABLE SQL字符串中检索表名,我相信它将涵盖大多数(如果不是全部)这些问题。下面是这样一种方法:

public String getTableNameFromCreate(final String sqlString) {
    // Always rememeber...we're only trying to get the table
    // name from the SQL String. We really don't care anything
    // about the rest of the SQL string.
    String tableName;
    String wrkStrg = sqlString.replace("[", "").replace("]", "").trim();
    // Is "CREATE TABLE" only
    if (wrkStrg.startsWith("CREATE TABLE ")) {
        wrkStrg = wrkStrg .substring(13).trim();
    }
    else if (wrkStrg.startsWith("CREATE GLOBAL TEMPORARY TABLE ")) {
        wrkStrg = wrkStrg .substring(30).trim();
    }
    else if (wrkStrg.startsWith("CREATE TEMPORARY TABLESPACE ")) {
        wrkStrg = wrkStrg .substring(28).trim();
    }

    // Is it Create Table ... AS, AS SELECT, PARALLEL COMPRESS AS,
    // or PARALLEL COMPRESS AS SELECT?
    if (wrkStrg.toUpperCase().contains(" PARALLEL COMPRESS ")) {
        wrkStrg = wrkStrg.replace(" parallel compress ", " PARALLEL COMPRESS ");
        tableName = wrkStrg.substring(0, wrkStrg.indexOf(" PARALLEL COMPRESS ")).trim();
    }
    else if (wrkStrg.toUpperCase().contains(" AS ")) {
        wrkStrg = wrkStrg.replace(" as ", " AS ");
        tableName = wrkStrg.substring(0, wrkStrg.indexOf(" AS ")).trim();
    }
    // Nope...none of that in the SQL String.
    else {
        tableName = wrkStrg.substring(0, wrkStrg.indexOf("(")).trim();
    }

    // return but remove quotes first if any...
    return tableName.replace("\"","").replace("'", "");
}


如果像您的示例(test_database.test_table)一样将数据库名称附加到表名称,那么您当然需要进一步解析实际的表名称。

关于java - 如何使用Hibernate从CREATE语句解析表名?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41783875/

10-16 21:53