본문 바로가기
MySql

MySQL 테이블이있는 경우 Java mysql

by 베이스 공부 2020. 12. 20.
반응형

지금까지 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)"
    + ")";

겸손한 해킹은 제공되는 모든 도움을 고맙게 생각합니다.

 

해결 방법

 

두 가지 접근 방식이 있습니다.


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


DROP TABLE IF EXISTS AgentDetail

테이블 쿼리를 생성하기 전에 (이렇게하면 테이블의 기존 데이터가 모두 삭제됩니다)

 

참조 페이지 https://stackoverflow.com/questions/19498520

 

 

반응형

댓글