2014-04-10 1 views
0

는 내가 텍스트 필드에서 값을 읽어 새 데이터베이스를 만들었습니다. 데이터베이스를 성공적으로 만들었습니다. 그러나 이미 같은 이름의 데이터베이스가 있으면 오류가 발생합니다. 그래서 데이터베이스 생성 여부를 확인하기로 결정했습니다. 그것을 어떻게 확인할 수 있습니까?데이터베이스가 존재하는지 여부를 확인하기 위해 SQL 쿼리는 무엇입니까? 내 프로그램에서

테이블에 데이터베이스가 있는지 여부를 확인하는 방법을 알고 있습니다. 내 코드는 다음과 같습니다. -

 preparedStatement = connect 
       .prepareStatement("SELECT count(*)FROM information_schema.tables\n" + 
        "WHERE table_schema = 'project' AND table_name = 'user'"); 
     rs=preparedStatement.executeQuery(); 
     rs.next(); 
     int chk = rs.getInt(1); 

     if(chk!=1) 
     { 
      preparedStatement = connect 
       .prepareStatement("create table user (staffname varchar(30) primary key)"); 
      preparedStatement.executeUpdate(); 
     } 

나는 이렇게합니다. 따라서 데이터베이스가 존재하는지 여부를 확인하는 방법을 알려주십시오.

이 코드가 작동합니까? -

당신은이 쿼리를 실행할 수 있습니다
preparedStatement = connect 
       .prepareStatement("SELECT count(*)FROM information_schema\n" + 
        "WHERE table_schema = "+dbName+""); 
     rs=preparedStatement.executeQuery(); 
     rs.next(); 
     int chk = rs.getInt(1); 

     if(chk!=1) 
     {    
     int resultset = statement.executeUpdate("create database " + dbName); 

     connect = DriverManager 
       .getConnection("jdbc:mysql://localhost:3306/"+dbName+"?" 
         + "user=root&password=virus"); 
     statement = connect.createStatement(); 
     } 
+0

"데이터베이스"와 "테이블"용어를 혼동하지 마십시오? – zerkms

답변

1

: 결과가 존재 한 경우

SELECT COUNT(*) 
FROM information_schema.tables 
WHERE table_schema = '[database name]' 

합니다.

당신은 또한 사용할 수 있습니다

SHOW DATABASES LIKE 'dbname'; 

을가 존재하는 경우, 당신은 하나 개의 행을 얻을.

관련 문제