I am trying to create a database and table from within my Java code to no avail. Here is my database code and the error I am receiving when I run my program. When I debug my PreparedStatement variables are null.
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 = ?";
}
Here is the error:
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.a开发者_StackOverflow社区pache.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
Any ideas what is going on? I have derby.jar in my libraries.
Your code says "if ! dbExists then createDatabase". Perhaps dbExists is returning TRUE when you have a fresh empty database, and so you're not calling createDatabase, and hence not calling createTables.
How does your db URL look like? It should have a ";create=true" at the end...
BTW, consider using JPA instead of plain JDBC
The code example doesnt seem complete, the crash occurs in getListEntries, but this is never called in the code listed above.
You're doing some truly awful things with catch blocks. You should edit every single one so they all print or log the stack trace. An empty catch block means an exception could be thrown but you'll never know it.
Why do you think you need to create the tables in the Java code? With most applications the schema is designed and implemented by a DBA so it's already in place when the Java application begins. Why must you create the tables at runtime? Should be done once.
精彩评论