Programing

테이블이 있는지 확인

lottogame 2020. 10. 7. 07:12
반응형

테이블이 있는지 확인 [중복]


이 질문에 이미 답변이 있습니다.

데이터베이스가 내장 된 데스크톱 애플리케이션이 있습니다. 프로그램을 실행할 때 특정 테이블이 존재하는지 확인하거나 그렇지 않은 경우 생성해야합니다.

내 데이터베이스에 대해 conn이라는 연결 개체가 주어지면 어떻게 확인할 수 있습니까?


사용 가능한 메타 데이터를 사용할 수 있습니다.

  DatabaseMetaData meta = con.getMetaData();
  ResultSet res = meta.getTables(null, null, "My_Table_Name", 
     new String[] {"TABLE"});
  while (res.next()) {
     System.out.println(
        "   "+res.getString("TABLE_CAT") 
       + ", "+res.getString("TABLE_SCHEM")
       + ", "+res.getString("TABLE_NAME")
       + ", "+res.getString("TABLE_TYPE")
       + ", "+res.getString("REMARKS")); 
  }

자세한 내용은 여기 를 참조하십시오. JavaDoc의주 의 사항도 참고하십시오 .


DatabaseMetaData dbm = con.getMetaData();
// check if "employee" table is there
ResultSet tables = dbm.getTables(null, null, "employee", null);
if (tables.next()) {
  // Table exists
}
else {
  // Table does not exist
}

여기에 제시된 솔루션이 완전히 완성되지 않았으므로 직접 추가하겠습니다. 여기에 새로운 것은 없습니다. 제시된 다른 솔루션과 다양한 주석에서이를 함께 연결할 수 있습니다.

확인해야 할 사항은 최소한 두 가지입니다.

  1. null 값을 전달하는 대신 getTables()메서드에 테이블 이름을 전달해야합니다. 첫 번째 경우에는 데이터베이스 서버가 결과를 필터링하도록하고 두 번째 경우에는 서버의 모든 테이블 목록을 요청한 다음 목록을 로컬로 필터링합니다. 전자는 단일 테이블 만 검색하는 경우 훨씬 빠릅니다.

  2. 같음이 일치하는 결과 집합에서 테이블 이름을 확인하십시오. 그 이유는 getTables()테이블에 대한 쿼리에서 패턴 일치를 수행하고 _문자가 SQL의 와일드 카드이기 때문입니다. 라는 테이블이 있는지 확인한다고 가정합니다 EMPLOYEE_SALARY. 그런 다음 EMPLOYEESSALARY원하는 것이 아닌 일치 항목 얻을 수 있습니다.

아, 그리고 그 결과 세트를 닫는 것을 잊지 마십시오. Java 7 이후로 try-with-resources 문 을 사용하고 싶을 것 입니다.

다음은 완전한 솔루션입니다.

public static boolean tableExist(Connection conn, String tableName) throws SQLException {
    boolean tExists = false;
    try (ResultSet rs = conn.getMetaData().getTables(null, null, tableName, null)) {
        while (rs.next()) { 
            String tName = rs.getString("TABLE_NAME");
            if (tName != null && tName.equals(tableName)) {
                tExists = true;
                break;
            }
        }
    }
    return tExists;
}

호출시 types매개 변수 (4 번째 매개 변수) 로 전달하는 것을 고려할 수 있습니다 getTables(). 일반적으로 나는 null당신이 자신을 제한하고 싶지 않기 때문에 그냥 떠날 것입니다. VIEW는 TABLE만큼 좋습니다. 요즘 많은 데이터베이스에서 VIEW를 통해 업데이트 할 수 있으므로 자신을 TABLE 유형으로 만 제한하는 것은 대부분의 경우 갈 길이 아닙니다. YMMV.


Gaby의 게시물에 추가하면 Oracle 10g 용 jdbc getTables ()가 작동하려면 모든 대문자가 필요합니다.

"employee" -> "EMPLOYEE"

그렇지 않으면 예외가 발생합니다.

java.sql.SqlExcepcion 소진 된 결과 집합

( "employee"가 스키마에 있더라도)


    /**
 * Method that checks if all tables exist
 * If a table doesnt exist it creates the table
 */
public void checkTables() {
    try {
        startConn();// method that connects with mysql database
        String useDatabase = "USE " + getDatabase() + ";";
        stmt.executeUpdate(useDatabase);
        String[] tables = {"Patients", "Procedures", "Payments", "Procedurables"};//thats table names that I need to create if not exists
        DatabaseMetaData metadata = conn.getMetaData();

        for(int i=0; i< tables.length; i++) {
            ResultSet rs = metadata.getTables(null, null, tables[i], null);
            if(!rs.next()) {
                createTable(tables[i]);
                System.out.println("Table " + tables[i] + " created");
            }
        }
    } catch(SQLException e) {
        System.out.println("checkTables() " + e.getMessage());
    }
    closeConn();// Close connection with mysql database
}

If using jruby, here is a code snippet to return an array of all tables in a db.

require "rubygems"
require "jdbc/mysql"
Jdbc::MySQL.load_driver
require "java"

def get_database_tables(connection, db_name)
  md = connection.get_meta_data
  rs = md.get_tables(db_name, nil, '%',["TABLE"])

  tables = []
  count = 0
  while rs.next
    tables << rs.get_string(3)
  end #while
  return tables
end

참고URL : https://stackoverflow.com/questions/2942788/check-if-table-exists

반응형