2013-10-04 43 views
0

我正在研究Java中的測驗類型應用程序。我正在考慮一個數據庫來保存問題,他們的難度和4個多項選擇項,也許還可以讓用戶在數據庫中爲他們的朋友創建他們自己的問題以供嘗試。我目前寫的代碼工作我IDE中:持久性Java數據庫

public class Database { 
    Connection conn=null; 
    String url="jdbc:derby://localhost:1527/Millionaire"; 
    String username="luke"; 
    String password="bigwood"; 
    private ArrayList<String> arrayGot = new ArrayList<>(); 

    Database(){ 
     try { 
     conn = DriverManager.getConnection(url, username, password); 
     } 
     catch (Throwable ex) { 
     System.err.println("SQL Exception: " + ex.getMessage()); 
     } 
    } 

    public ArrayList<String> getQuestions(int difficulty) throws SQLException{ 
     arrayGot.clear(); 
     Statement stmt = conn.createStatement(); 
      String SQLCommand ="select * from LUKE.QUESTIONS where difficulty="+difficulty; 
      ResultSet rs = stmt.executeQuery(SQLCommand); 
      while(rs.next()){ 
       String question = rs.getString("Question"); 
       arrayGot.add(question); 
       question = rs.getString("Answer1"); 
       arrayGot.add(question); 
       question = rs.getString("Answer2"); 
       arrayGot.add(question); 
       question = rs.getString("Answer3"); 
       arrayGot.add(question); 
       question = rs.getString("Answer4"); 
       arrayGot.add(question); 
      } 

     return arrayGot; 
    } 
} 

我想不過知道有一個簡單的方法,使我的IDE(NetBeans的)以外這項工作。一旦編譯完成,我希望數據庫在.jar結束的任何計算機上都可讀寫。什麼是實施這個最好的方法?

提前喝彩, 盧克。

+0

我的事,你不設置您的罐子類路徑。 –

回答

1

您可以設置德比在embedded mode運行,這將讓你獨立於其他服務的運行。請記住,您需要在代碼中處理數據庫表的初始化。用於連接

public static Connection Connect(){ 


try { 

    Class.forName("oracle.jdbc.driver.OracleDriver"); 

} catch (ClassNotFoundException e) { 

    System.out.println("Where is your Oracle JDBC Driver?"); 
    e.printStackTrace(); 
    return null; 

} 

System.out.println("Oracle JDBC Driver Registered!"); 

Connection connection = null; 

try { 

    connection = DriverManager.getConnection(
      "YOUR JDBC URL", "USERNAME", 
      "PASSWORD"); 

} catch (SQLException e) { 

    System.out.println("Connection Failed! Check output console"); 
    e.printStackTrace(); 
    return null; 

} 



return connection; 

}

+0

沒錯,所以這會讓我使用應用程序傳輸數據庫,還是每次我想使用數據庫時都需要重新創建數千(可能)的單元格? –

+0

AFAIK由於磁盤格式穩定,您可以分發預製數據庫。您還可以分發壓縮的SQL轉儲,或從網絡獲取它們(自動更新?)。 –

-1

示例代碼嘗試用你的數據庫屬性