2017-11-27 1 views
0

많은 H2 데이터베이스 튜토리얼에서 서핑을하니 기본적으로 데이터베이스에 마지막 연결을 닫으면 데이터베이스가 닫힙니다. 메모리 내 데이터베이스의 경우 이는 내용이 손실되었음을 의미합니다.연결을 닫은 후에도 h2 데이터베이스 테이블에 데이터가 여전히 존재합니다

Employee1 테이블을 만들고 레코드를 삽입하고 연결을 종료했습니다. 그러나 나는 언젠가 후에 동일한 데이터베이스에 다시 연결하면 여전히 Employee1 데이터를 검색 할 수 있습니다. 왜 데이터가 아직 존재합니까? 위의 프로그램의

package connection; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 

public class Connector { 

static Connection conn = null; 
static Statement stmt = null; 

public static void main(String[] args) { 

    System.out.println("Welcome!"); 
    Connector connector = new Connector(); 
    connector.createConnection(); 
    connector.createTable("Employee2"); 
    connector.insertRecord("Employee2"); 
    connector.readRecord("Employee2"); 
    connector.readRecord("Employee1"); //Employee1 Table which is created in previous execution but still it reads the data 
    connector.closeConnection(); 
} 

public void createConnection() { 
    try { 
     System.out.println("Creating connection"); 
     // STEP 1: Register JDBC driver 
     Class.forName("org.h2.Driver"); 
     // STEP 2: Open a connection 
     System.out.println("Connecting to database..."); 
     conn = DriverManager.getConnection("jdbc:h2:mem/db1", "sa", ""); 
    } catch (SQLException se) { 
     // Handle errors for JDBC 
     se.printStackTrace(); 
    } catch (Exception e) { 
     // Handle errors for Class.forName 
     e.printStackTrace(); 
    } 

} 

public void createTable(String tableName) { 
    try { 
     // STEP 3: Execute a query 
     System.out.println("Creating table in given database with the name of ..." + tableName); 
     stmt = conn.createStatement(); 
     String sql = "CREATE TABLE " + tableName + "(id INTEGER not NULL, " + " first VARCHAR(255), " 
       + " last VARCHAR(255), " + " age INTEGER, " + " PRIMARY KEY (id))"; 
     stmt.executeUpdate(sql); 
     System.out.println("Created table in given database..."); 

    } catch (SQLException se) { 
     // Handle errors for JDBC 
     se.printStackTrace(); 
    } catch (Exception e) { 
     // Handle errors for Class.forName 
     e.printStackTrace(); 
    } 
} 

public void insertRecord(String tableName) { 
    try { 
     // STEP 3: Execute a query 
     stmt = conn.createStatement(); 
     String sql = "INSERT INTO " + tableName + " VALUES (500, 'Zara', 'Ali', 18)"; 

     stmt.executeUpdate(sql); 
     sql = "INSERT INTO " + tableName + " VALUES (501, 'Mahnaz', 'Fatma', 25)"; 

     stmt.executeUpdate(sql); 
     sql = "INSERT INTO " + tableName + " VALUES (502, 'Zaid', 'Khan', 30)"; 

     stmt.executeUpdate(sql); 
     sql = "INSERT INTO " + tableName + " VALUES(503, 'Sumit', 'Mittal', 28)"; 

     stmt.executeUpdate(sql); 
     System.out.println("Inserted records into the table..."); 
    } catch (SQLException se) { 
     // Handle errors for JDBC 
     se.printStackTrace(); 
    } catch (Exception e) { 
     // Handle errors for Class.forName 
     e.printStackTrace(); 
    } 
} 

public void readRecord(String tableName) { 
    try { 
     System.out.println("Reading data from "+tableName); 
     stmt = conn.createStatement(); 
     String sql = "SELECT id, first, last, age FROM " + tableName; 
     ResultSet rs = stmt.executeQuery(sql); 

     // STEP 4: Extract data from result set 
     while (rs.next()) { 
      // Retrieve by column name 
      int id = rs.getInt("id"); 
      int age = rs.getInt("age"); 
      String first = rs.getString("first"); 
      String last = rs.getString("last"); 

      // Display values 
      System.out.print("ID: " + id); 
      System.out.print(", Age: " + age); 
      System.out.print(", First: " + first); 
      System.out.println(", Last: " + last); 
     } 
     // STEP 5: Clean-up environment 
     rs.close(); 
    } catch (SQLException se) { 
     // Handle errors for JDBC 
     se.printStackTrace(); 
    } catch (Exception e) { 
     // Handle errors for Class.forName 
     e.printStackTrace(); 
    } finally { 
     // finally block used to close resources 
     try { 
      if (stmt != null) 
       stmt.close(); 
     } catch (SQLException se2) { 
     } // nothing we can do 
    } // end try 
} 

public void closeConnection() { 
    try { 
     if (conn != null) { 
      conn.close(); 
      System.out.println("Connection Closed.."); 
     } 
    } catch (SQLException se) { 
     se.printStackTrace(); 
    } // end finally try 
} 
} 

출력 :

Welcome! 
Creating connection 
Connecting to database... 
Creating table in given database with the name of ...Employee2 
Created table in given database... 
Inserted records into the table... 
Reading data from Employee2 
ID: 500, Age: 18, First: Zara, Last: Ali 
ID: 501, Age: 25, First: Mahnaz, Last: Fatma 
ID: 502, Age: 30, First: Zaid, Last: Khan 
ID: 503, Age: 28, First: Sumit, Last: Mittal 
Reading data from Employee1 
ID: 400, Age: 18, First: freeze, Last: Ali 
ID: 401, Age: 25, First: dora, Last: Fatma 
ID: 402, Age: 30, First: xer, Last: Khan 
ID: 403, Age: 28, First: kilo, Last: Mittal 
Connection Closed.. 
+0

참조 : https://stackoverflow.com/questions/ 27057900/in-memory-database-h2-how-long-keep-connection-open – duffymo

+0

사실 내 문제는 연결을 닫은 후에도 내용이 손실되지 않고 여전히 존재합니다. 심지어 나는 conn = DriverManager.getConnection ("jdbc : h2 : mem/db1; DB_CLOSE_DELAY = 0", "sa", "");을 시도했다. 그러나 그것은 작동하지 않습니다. – KarthikaSrinivasan

+0

문제를 이해합니다. 나는 설명이 없다. – duffymo

답변

2

당신이 here

jdbc:h2:mem/db1 

을 볼 수 있듯이 그렇게 mem/db1의 상대 경로 데이터와 로컬 데이터베이스에 파일를 연결합니다 파일이 저장된 이유는 여전히 존재합니다. 메모리 데이터베이스에 대한

연결 문자열은 다음과 같아야합니다 이들 중 하나가 설정되어있는 경우

jdbc:h2:mem:db1 

공지 사항 /:의 차이는

+0

고마워. 실수로 이어지는 코드를 혼동하고 편집하는 일이 많았습니다. – KarthikaSrinivasan

관련 문제