3

感谢迄今为止在我用 MySQL 学习 Java 的史诗般的战斗中的所有支持。我想要做的是检查表是否存在。当前发生的情况是,如果创建了数据库并且也创建了表。但是如果我运行相同的代码,我会得到一个表已经存在的错误。

最大的问题是我将如何检查表是否存在?这是我处理过的一些代码

if (tabCrea.createTable(dbDef, con, preStatement, tabStruct.getAgentDetail(), "Agent Details"))
    System.out.println("Passed Here");
else
    System.out.println("Failed Here");

调用以下内容

protected boolean createTable(DataBaseDefaults dbDef, Connection con, Statement statement, String myTableName, String tableName) {

    try {
        Class.forName(dbDef.getJdbcDriver());
        con = DriverManager.getConnection(dbDef.getDbAddress() + dbDef.getPortAddress() + dbDef.getDbName(), 
                dbDef.getDbUserName(), dbDef.getDbPassword());
        statement = con.createStatement();
        statement.executeUpdate(myTableName);
        System.out.println("Table Sucessfully Created : " + tableName);
        return true;
    }
    catch (SQLException e ) {
        //Problem is caught here;
        System.out.println("An error has occured on Table Creation with Table " + tableName);
        return false;
    }
    catch (ClassNotFoundException e) {
        System.out.println("There was no Mysql drivers found");
        return false;
    }
}

并且表在这里定义

private String agentDetail = "CREATE TABLE AgentDetail ("
    + "AgentDetailIdNo INT(64) NOT NULL AUTO_INCREMENT,"
    + "Initials VARCHAR(2),"
    + "AgentDetailDate DATE,"
    + "AgentDetailCount INT(64),"
    + "PRIMARY KEY(AgentDetailIdNo)"
    + ")";

一个不起眼的黑客将不胜感激所提供的任何帮助。

4

4 回答 4

8

有两种方法:

1)如果您想保留该表(如果它确实存在),请使用IF NOT EXISTS

private String agentDetail = "CREATE TABLE IF NOT EXISTS AgentDetail (" ...

2)如果要删除表重新开始,先用DROP TABLE语句删除表。为此,请运行语句

DROP TABLE IF EXISTS AgentDetail

在创建表查询之前(请注意,这将删除表中的所有现有数据)

于 2013-10-21T15:32:23.480 回答
1

您可以使用CREATE TABLE IF NOT EXISTS TBL_NAME

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
    (create_definition,...)
    [table_options]
    [partition_options]
于 2013-10-21T15:25:25.497 回答
1

DatabaseMetaData API 是 JDBC 规范的一部分,是在 Java 中执行此操作的方法。你会特别想查看`getTables' 方法。这是一门很好熟悉的课程。

于 2013-10-21T16:10:53.163 回答
1

您可以使用

SHOW TABLES LIKE '$this_table'  or
SHOW TABLES FROM $dbname 

并检查表是否已经存在

于 2013-10-21T15:28:04.723 回答