我试图从我的Java代码中创建一个数据库和表无济于事。这是我的数据库代码和运行程序时收到的错误。当我调试PreparedStatement时,变量为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 = ?";
}
这是错误:
运行: java.sql.SQLSyntaxErrorException:表/视图'APP.REQUIREMENTS'不存在。 at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(未知来源) 在org.apache.derby.impl.jdbc.Util.generateCsSQLException(未知来源) at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(未知来源) at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(未知来源) at org.apache.derby.impl.jdbc.EmbedConnection.handleException(未知来源) at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown Source) 在org.apache.derby.impl.jdbc.EmbedStatement.execute(未知来源) at org.apache.derby.impl.jdbc.EmbedStatement.executeQuery(Unknown Source) at com.example.requirements.db.RecordDao.getListEntries(RecordDao.java:240) 在com.example.requirements.RequirementsFrame。(RequirementsFrame.java:42) 在com.example.requirements.RequirementsFrame.main(RequirementsFrame.java:182) 引起:java.sql.SQLException:表/视图'APP.REQUIREMENTS'不存在。 at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(未知来源) at org.apache.derby.impl.jdbc.SQLExceptionFactory40.wrapArgsForTransportAcrossDRDA(Unknown Source) ......还有11个 引起:ERROR 42X05:表/视图'APP.REQUIREMENTS'不存在。 at org.apache.derby.iapi.error.StandardException.newException(Unknown Source) 在org.apache.derby.impl.sql.compile.FromBaseTable.bindTableDescriptor(未知来源) at org.apache.derby.impl.sql.compile.FromBaseTable.bindNonVTITables(未知来源) 在org.apache.derby.impl.sql.compile.FromList.bindTables(未知来源) 在org.apache.derby.impl.sql.compile.SelectNode.bindNonVTITables(未知来源) 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) 在org.apache.derby.impl.sql.GenericStatement.prepare(未知来源) at org.apache.derby.impl.sql.conn.GenericLanguageConnectionContext.prepareInternalStatement(Unknown Source) ......还有5个
任何想法是怎么回事?我的图书馆里有derby.jar。
答案 0 :(得分:1)
您的代码显示“if!dbExists then createDatabase”。当你有一个新的空数据库时,dbExists可能会返回TRUE,因此你不会调用createDatabase,因此不会调用createTables。
答案 1 :(得分:0)
您的数据库网址如何?它最后应该有一个“; create = true”......
BTW,考虑使用JPA而不是普通的JDBC答案 2 :(得分:0)
代码示例似乎并不完整,崩溃发生在getListEntries中,但从未在上面列出的代码中调用过。
答案 3 :(得分:-1)
你正在用catch块做一些非常糟糕的事情。您应该编辑每一个,以便它们都打印或记录堆栈跟踪。一个空的catch块意味着可以抛出异常,但你永远不会知道它。
为什么您认为需要在Java代码中创建表?对于大多数应用程序,架构由DBA设计和实现,因此在Java应用程序开始时它已经存在。为什么必须在运行时创建表?应该做一次。