如果表存在,则为Java mysql

K S*_*ggs 3 java mysql sql jdbc

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

最大的问题是我如何检查表存在?这是我工作过的一些代码

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

其中称之为以下内容

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

并在此处定义表格

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

一个卑微的黑客会感谢任何提供的帮助.

She*_*tJS 8

有两种方法:

1)如果要保留表(如果存在),请使用IF NOT EXISTS:

private String agentDetail = "CREATE TABLE IF NOT EXISTS AgentDetail (" ...
Run Code Online (Sandbox Code Playgroud)

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

DROP TABLE IF EXISTS AgentDetail
Run Code Online (Sandbox Code Playgroud)

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