2010-11-23 29 views
0

我想從我的Java代碼中創建數據庫和表無濟於事。這是我的數據庫代碼和我在運行程序時收到的錯誤。當我調試我的PreparedStatement變量是空的。德比表未創建

public class RecordDao { 

/** Creates a new instance of RecordDao */ 
public RecordDao() { 
    this("Requirements"); 
} 

public RecordDao(String requirements) { 
    this.dbName = requirements; 

    setDBSystemDir(); 
    dbProperties = loadDBProperties(); 
    String driverName = dbProperties.getProperty("derby.driver"); 
    loadDatabaseDriver(driverName); 
    if(!dbExists()) { 
     createDatabase(); 
    } 

} 

private boolean dbExists() { 
    boolean bExists = false; 
    String dbLocation = getDatabaseLocation(); 
    File dbFileDir = new File(dbLocation); 
    if (dbFileDir.exists()) { 
     bExists = true; 
    } 
    return bExists; 
} 

private void setDBSystemDir() { 
    // decide on the db system directory 
    String userHomeDir = System.getProperty("user.home", "."); 
    String systemDir = userHomeDir + "/.requirementsspecs"; 
    System.setProperty("derby.system.home", systemDir); 

    // create the db system directory 
    File fileSystemDir = new File(systemDir); 
    fileSystemDir.mkdir(); 
} 

private void loadDatabaseDriver(String driverName) { 
    // load Derby driver 
    try { 
     Class.forName(driverName); 
    } catch (ClassNotFoundException ex) { 
     ex.printStackTrace(); 
    } 

} 

private Properties loadDBProperties() { 
    InputStream dbPropInputStream = null; 
    dbPropInputStream = RecordDao.class.getResourceAsStream("Configuration.properties"); 
    dbProperties = new Properties(); 
    try { 
     dbProperties.load(dbPropInputStream); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } 
    return dbProperties; 
} 


private boolean createTables(Connection dbConnection) { 
    boolean bCreatedTables = false; 
    Statement statement = null; 
    try { 
     statement = dbConnection.createStatement(); 
     statement.execute(strCreateRequirementsTable); 
     bCreatedTables = true; 
    } catch (SQLException ex) { 
     ex.printStackTrace(); 
    } 

    return bCreatedTables; 
} 
private boolean createDatabase() { 
    boolean bCreated = false; 
    Connection dbConnection = null; 

    String dbUrl = getDatabaseUrl(); 
    dbProperties.put("create", "true"); 

    try { 
     System.out.println("inside try statement to create database"); 
     dbConnection = DriverManager.getConnection(dbUrl, dbProperties); 
     bCreated = createTables(dbConnection); 
    } catch (SQLException ex) { 
    } 
    dbProperties.remove("create"); 
    return bCreated; 
} 


public boolean connect() { 
    String dbUrl = getDatabaseUrl(); 
    try { 
     dbConnection = DriverManager.getConnection(dbUrl, dbProperties); 
     stmtSaveNewRecord = dbConnection.prepareStatement(strSaveRecord, Statement.RETURN_GENERATED_KEYS); 
     stmtUpdateExistingRecord = dbConnection.prepareStatement(strUpdateRecord); 
     stmtGetRecord = dbConnection.prepareStatement(strGetRecord); 
     stmtDeleteRecord = dbConnection.prepareStatement(strDeleteRecord); 

     isConnected = dbConnection != null; 
    } catch (SQLException ex) { 
     isConnected = false; 
    } 
    return isConnected; 
} 

private String getHomeDir() { 
    return System.getProperty("user.home"); 
} 

public void disconnect() { 
    if(isConnected) { 
     String dbUrl = getDatabaseUrl(); 
     dbProperties.put("shutdown", "true"); 
     try { 
      DriverManager.getConnection(dbUrl, dbProperties); 
     } catch (SQLException ex) { 
     } 
     isConnected = false; 
    } 
} 

public String getDatabaseLocation() { 
    String dbLocation = System.getProperty("derby.system.home") + "/" + dbName; 
    return dbLocation; 
} 

public String getDatabaseUrl() { 
    String dbUrl = dbProperties.getProperty("derby.url") + dbName; 
    return dbUrl; 
} 


public int saveRecord(RequirementsData record) { 
    int id = -1; 
    try { 
     stmtSaveNewRecord.clearParameters(); 
     stmtSaveNewRecord.setString(1, record.getDescription()); 
     stmtSaveNewRecord.setString(2, record.getType()); 
     stmtSaveNewRecord.setString(3, record.getStatus()); 
     stmtSaveNewRecord.setString(4, record.getPriority()); 
     stmtSaveNewRecord.setString(5, record.getDifficulty()); 
     stmtSaveNewRecord.setString(6, record.getDueDate()); 
     stmtSaveNewRecord.setString(7, record.getCreatedOn()); 
     int rowCount = stmtSaveNewRecord.executeUpdate(); 
     ResultSet results = stmtSaveNewRecord.getGeneratedKeys(); 
     if (results.next()) { 
      id = results.getInt(1); 
     } 

    } catch(SQLException sqle) { 
     sqle.printStackTrace(); 
    } 
    return id; 
} 

public boolean editRecord(RequirementsData record) { 
    boolean bEdited = false; 
    try { 
     stmtUpdateExistingRecord.clearParameters(); 

     stmtUpdateExistingRecord.setString(1, record.getDescription()); 
     stmtUpdateExistingRecord.setString(2, record.getType()); 
     stmtUpdateExistingRecord.setString(3, record.getStatus()); 
     stmtUpdateExistingRecord.setString(4, record.getPriority()); 
     stmtUpdateExistingRecord.setString(5, record.getDifficulty()); 
     stmtUpdateExistingRecord.setString(6, record.getDueDate()); 
     stmtUpdateExistingRecord.setString(7, record.getCreatedOn()); 
     stmtUpdateExistingRecord.setInt(12, record.getId()); 
     stmtUpdateExistingRecord.executeUpdate(); 
     bEdited = true; 
    } catch(SQLException sqle) { 
     sqle.printStackTrace(); 
    } 
    return bEdited; 

} 

public boolean deleteRecord(int id) { 
    boolean bDeleted = false; 
    try { 
     stmtDeleteRecord.clearParameters(); 
     stmtDeleteRecord.setInt(1, id); 
     stmtDeleteRecord.executeUpdate(); 
     bDeleted = true; 
    } catch (SQLException sqle) { 
     sqle.printStackTrace(); 
    } 

    return bDeleted; 
} 

public boolean deleteRecord(RequirementsData record) { 
    int id = record.getId(); 
    return deleteRecord(id); 
} 

public List<ListEntry> getListEntries() { 
    List<ListEntry> listEntries = new ArrayList<ListEntry>(); 
    Statement queryStatement = null; 
    ResultSet results = null; 

    try { 
     queryStatement = dbConnection.createStatement(); 
     results = queryStatement.executeQuery(strGetListEntries); 
     while(results.next()) { 
      int id = results.getInt(1); 
      String description = results.getString(2); 
      String type = results.getString(3); 
      String dueDate = results.getString(4); 

      ListEntry entry = new ListEntry(description, type, dueDate, id); 
      listEntries.add(entry); 
     } 

    } catch (SQLException sqle) { 
     sqle.printStackTrace(); 

    } 

    return listEntries; 
} 

public RequirementsData getRecord(int index) { 
    RequirementsData record = null; 
    try { 
     stmtGetRecord.clearParameters(); 
     stmtGetRecord.setInt(1, index); 
     ResultSet result = stmtGetRecord.executeQuery(); 
     if (result.next()) { 
      String description = result.getString("DESCRIPTION"); 
      String type = result.getString("TYPE"); 
      String status = result.getString("STATUS"); 
      String priority = result.getString("PRIORITY"); 
      String difficulty = result.getString("DIFFICULTY"); 
      String dueDate = result.getString("DUEDATE"); 
      String createdOn = result.getString("CREATEDON"); 
      int id = result.getInt("ID"); 
      record = new RequirementsData(description, type, status, priority, 
        difficulty, dueDate, createdOn, id); 
     } 
    } catch(SQLException sqle) { 
     sqle.printStackTrace(); 
    } 

    return record; 
} 

public static void main(String[] args) { 
    RecordDao db = new RecordDao(); 
    System.out.println("######"+ db.getDatabaseLocation()); 
    System.out.println(db.getDatabaseUrl()); 
    db.connect(); 
    db.disconnect(); 
} 


private Connection dbConnection; 
private Properties dbProperties; 
private boolean isConnected; 
private String dbName; 
private PreparedStatement stmtSaveNewRecord; 
private PreparedStatement stmtUpdateExistingRecord; 
private PreparedStatement stmtGetListEntries; 
private PreparedStatement stmtGetRecord; 
private PreparedStatement stmtDeleteRecord; 

private static final String strCreateRequirementsTable = 
     "create table APP.REQUIREMENTS (" + 
     " ID    INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)," + 
     " DESCRIPTION VARCHAR(300), " + 
     " TYPE   VARCHAR(15), " + 
     " STATUS   VARCHAR(15), " + 
     " PRIORITY  VARCHAR(15), " + 
     " DIFFICULTY  VARCHAR(15), " + 
     " DUEDATE  VARCHAR(30), " + 
     " CREATEDON  VARCHAR(30), " + 
     ")"; 

private static final String strGetRecord = 
     "SELECT * FROM APP.REQUIREMENTS " + 
     "WHERE ID = ?"; 

private static final String strSaveRecord = 
     "INSERT INTO APP.REQUIREMENTS " + 
     " (DESCRIPTION, TYPE, STATUS, PRIORITY, DIFFICULTY, DUEDATE, CREATEDON) " + 
     "VALUES (?, ?, ?, ?, ?, ?, ?)"; 


private static final String strGetListEntries = 
     "SELECT ID, DESCRIPTION, TYPE, DUEDATE FROM APP.REQUIREMENTS " + 
     "ORDER BY DUEDATE ASC"; 

private static final String strUpdateRecord = 
     "UPDATE APP.REQUIREMENTS " + 
     "SET DESCRIPTION = ?, " + 
     " TYPE = ?, " + 
     " STATUS = ?, " + 
     " PRIORITY = ?, " + 
     " DIFFICULTY = ?, " + 
     " DUEDATE = ?, " + 
     " CREATEDON = ?, " + 
     "WHERE ID = ?"; 

private static final String strDeleteRecord = 
     "DELETE FROM APP.REQUIREMENTS " + 
     "WHERE ID = ?"; 

}

以下是錯誤:

run: java.sql.SQLSyntaxErrorException: Table/View 'APP.REQUIREMENTS' does not exist. at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source) at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source) at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source) at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source) at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source) at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown Source) at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source) at org.apache.derby.impl.jdbc.EmbedStatement.executeQuery(Unknown Source) at com.example.requirements.db.RecordDao.getListEntries(RecordDao.java:240) at com.example.requirements.RequirementsFrame.(RequirementsFrame.java:42) at com.example.requirements.RequirementsFrame.main(RequirementsFrame.java:182) Caused by: java.sql.SQLException: Table/View 'APP.REQUIREMENTS' does not exist. at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source) at org.apache.derby.impl.jdbc.SQLExceptionFactory40.wrapArgsForTransportAcrossDRDA(Unknown Source) ... 11 more Caused by: ERROR 42X05: Table/View 'APP.REQUIREMENTS' does not exist. at org.apache.derby.iapi.error.StandardException.newException(Unknown Source) at org.apache.derby.impl.sql.compile.FromBaseTable.bindTableDescriptor(Unknown Source) at org.apache.derby.impl.sql.compile.FromBaseTable.bindNonVTITables(Unknown Source) at org.apache.derby.impl.sql.compile.FromList.bindTables(Unknown Source) at org.apache.derby.impl.sql.compile.SelectNode.bindNonVTITables(Unknown Source) at org.apache.derby.impl.sql.compile.DMLStatementNode.bindTables(Unknown Source) at org.apache.derby.impl.sql.compile.DMLStatementNode.bind(Unknown Source) at org.apache.derby.impl.sql.compile.CursorNode.bindStatement(Unknown Source) at org.apache.derby.impl.sql.GenericStatement.prepMinion(Unknown Source) at org.apache.derby.impl.sql.GenericStatement.prepare(Unknown Source) at org.apache.derby.impl.sql.conn.GenericLanguageConnectionContext.prepareInternalStatement(Unknown Source) ... 5 more

任何想法是怎麼回事?我的圖書館裏有derby.jar。

回答

0

你正在用catch塊做一些真正糟糕的事情。您應該編輯每一個,以便全部打印或記錄堆棧跟蹤。一個空的catch塊意味着可以拋出異常,但你永遠不會知道它。

爲什麼你認爲你需要在Java代碼中創建表?對於大多數應用程序來說,架構是由DBA設計和實現的,因此在Java應用程序開始時已經存在。爲什麼你必須在運行時創建表?應該做一次。

+0

我正在做一個類的項目,我沒有訪問服務器,所以必須在我的程序中使用嵌入式數據庫(德比)。另外,我在那裏的代碼是我從Sun獲得的一個例子的一部分。 – taraloca 2010-11-25 04:53:57

0

你的db URL是怎麼樣的?它應該有一個「創建=真」的結尾......

順便說一句,可以考慮使用,而不是簡單的JDBC

+0

我不會向任何尚未掌握JDBC的人推薦JPA。 – duffymo 2010-11-25 12:45:18

0

的代碼示例JPA似乎沒有完整的,多發生在getListEntries崩潰,但這是從來沒有在上面列出的代碼中調用。

1

您的代碼顯示「if!dbExists then createDatabase」。也許dbExists在你有一個新的空數據庫時返回TRUE,所以你不調用createDatabase,因此不調用createTables。