簡體   English   中英

如果表存在,則為Java mysql

[英]Java mysql if Table Exists

感謝迄今為止我在用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)"
    + ")";

一個卑微的黑客會感謝任何提供的幫助。

有兩種方法:

1)如果你想保留表,如果它存在,使用IF NOT EXISTS

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

2)如果要刪除表並重新開始,請先使用DROP TABLE語句刪除該表。 為此,請運行該語句

DROP TABLE IF EXISTS AgentDetail

在創建表查詢之前(注意這將刪除表中的所有現有數據)

您可以使用CREATE TABLE IF NOT EXISTS TBL_NAME

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
    (create_definition,...)
    [table_options]
    [partition_options]

您可以使用

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

並檢查表是否已存在

DatabaseMetaData API是JDBC規范的一部分,是在Java中執行此操作的方法。 你特別想查看`getTables'方法。 這是一個很熟悉的好課程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM