2015-03-21 18 views
6

Tôi đang mã hóa ứng dụng máy khách-ứng dụng trong Java và tôi cần triển khai cơ sở dữ liệu cục bộ ở phía máy chủ và tôi quyết định chuyển sang cơ sở dữ liệu H2.Khởi động cơ sở dữ liệu H2 theo lập trình

Một điều nữa cần thêm là kết nối TCP của Hoa Kỳ để bắt đầu và chạy cơ sở dữ liệu. Đây là những gì tôi đặt lại với nhau cho đến nay:

Class.forName("org.h2.Driver"); 
Server server = Server.createTcpServer(DB_PATH).start(); 

Connection currentConn = DriverManager.getConnection(DB_PATH, DB_USER, DB_PASSWORD); 

Trường hợp chuỗi kết nối là jdbc:h2:tcp://localhost/~/test.

Đó đoạn mã trả về với một ngoại lệ:

Feature not supported: "jdbc:h2:tcp://localhost/~/test" [50100-176] 

Tôi đi theo this article.

Trả lời

11

Something như thế này nên làm việc

Server server = null; 
      try { 
       server = Server.createTcpServer("-tcpAllowOthers").start(); 
       Class.forName("org.h2.Driver"); 
       Connection conn = DriverManager. 
        getConnection("jdbc:h2:tcp://localhost/~/stackoverflow", "sa", ""); 
       System.out.println("Connection Established: " 
         + conn.getMetaData().getDatabaseProductName() + "/" + conn.getCatalog()); 

      } catch (Exception e) { 
       e.printStackTrace(); 

và đầu ra là kết nối thành lập: H2/Stackoverflow

này đã được thử nghiệm với h2-1.4.184

5

Đây là H2- đơn giản của tôi DBManager - chỉ cần đặt tên tệp là DBManager.java và vui lòng sử dụng lại nó:

import java.sql.SQLException; 

import org.h2.tools.Server; 

public class DBManager { 

    private static void startDB() throws SQLException { 
     Server.createTcpServer("-tcpPort", "9092", "-tcpAllowOthers").start(); 

    } 

    private static void stopDB() throws SQLException { 
     Server.shutdownTcpServer("tcp://localhost:9092", "", true, true); 
    } 

    public static void main(String[] args) { 

     try { 
      Class.forName("org.h2.Driver"); 

      if (args.length > 0) { 
       if (args[0].trim().equalsIgnoreCase("start")) { 
        startDB(); 
       } 

       if (args[0].trim().equalsIgnoreCase("stop")) { 
        stopDB(); 
       } 
      } else { 
       System.err 
         .println("Please provide one of following arguments: \n\t\tstart\n\t\tstop"); 
      } 

     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } 

} 
3

Tôi đã có thể làm điều đó dễ dàng hơn khi chấp nhận các giá trị mặc định:

 Server server = Server.createTcpServer().start(); 
Các vấn đề liên quan