2017-05-10 56 views
1

任務:如果數據庫不可用或損壞,請查找備份,如果存在,則將其複製爲主數據庫。如何防止JDBC創建數據庫?

目前,當我連接,如果沒有數據庫,它會自動創建:

Connection c = null; 
try { 
    Class.forName("org.sqlite.JDBC"); 
    c = DriverManager.getConnection("jdbc:sqlite:src/home/accounting/DB/myDatabase.sqlite"); 
    System.out.println("Opened database successfully"); 
    return c; 
} catch (Exception e) { 
    System.err.println(e.getClass().getName() + ": " + e.getMessage()); 
    return null; 
} 

我想防止數據庫被創建,確定是否數據庫不存在或已損壞,並觸發檢查備份數據庫的可用性。

+0

JDBC不創造任何東西。 MySQLLite驅動程序可能。 – EJP

回答

2

你必須檢查,如果你的數據庫退出與否的文件:

String dbPath = "src/home/accounting/DB/myDatabase.sqlite"; 
File dbFile = new File(dbPath); 
if (dbFile.exists()) { 
    //database already exist don't create it again 
} else { 
    Connection c = null; 
    try { 
     Class.forName("org.sqlite.JDBC"); 
     c = DriverManager.getConnection("jdbc:sqlite:" + dbPath); 
     System.out.println("Opened database successfully"); 
     return c; 
    } catch (ClassNotFoundException | SQLException e) { 
     System.err.println(e.getClass().getName() + ": " + e.getMessage()); 
     return null; 
    } 
} 
相關問題