2010-11-23 6 views
0

Javaコード内からデータベースとテーブルを作成しようとしています。私のプログラムを実行すると、データベースコードとエラーが表示されます。私がPreparedStatement変数をデバッグするとき、変数はnullです。ここでDerbyテーブルが作成されていません

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

あなたはキャッチブロックで本当にひどいことをしています。スタックトレースをすべて出力または記録するように、すべてのスタックを編集する必要があります。空のキャッチブロックとは、例外がスローされる可能性があることを意味します。

なぜJavaコードでテーブルを作成する必要があると思いますか?ほとんどのアプリケーションでは、スキーマはDBAによって設計され実装されるため、Javaアプリケーションの起動時にはすでに実装されています。なぜ実行時にテーブルを作成する必要がありますか?一度する必要があります。

+0

私はサーバーへのアクセス権がないクラスプロジェクトを行っているので、私のプログラムに組み込みのデータベース(Derby)を使用する必要があります。また、私が持っているコードは、私がSunから入手した例の一部です。 – taraloca

0

dbのURLはどのように見えますか?それは持つべき「を; create = trueを」最後に...

ところで、コード例では、完全に見えるdoes notの代わりにプレーンなJDBC

+0

JPAをまだ習得していない人にはJPAをお勧めしません。 – duffymo

+0

さて、まずJDBCとJPAを学び、次にJPAを使って実際のプロジェクトに取り組んでください;-) – Puce

0

のJPAの使用を検討して、クラッシュがgetListEntriesに発生するが、これは決してありません上記のコードで呼び出されます。

1

"if!dbExists then createDatabase"というコードが表示されます。おそらく、dbExistsは、空のデータベースが新しくなったときにTRUEを返します。したがって、createDatabaseを呼び出さず、createTablesを呼び出さないことになります。