我收到错误:
Exception in thread "main" java.lang.NullPointerException
at com.deanchester.minos.utils.DatabaseManager.createTables(DatabaseManager.java:59)
at com.deanchester.minos.tests.testAddContestantMethod.main(testAddContestantMethod.java:21)
我使用此方法创建连接:
private static final String driver = "org.apache.derby.jdbc.EmbeddedDriver";
private static final String protocol = "jdbc:derby:";
private static final Properties props = new Properties();
public static Connection getDatabaseConnection() {
try {
if(conn==null || conn.isClosed()) {
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(protocol+"minos;create:true;",props);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
我使用以下方法创建表:
private static final String tablesSQL = "CREATE TABLE `contestants` (`id` int(11) NOT NULL AUTO_INCREMENT,`first_name` varchar(100) DEFAULT NULL,`last_name` varchar(100) DEFAULT NULL, `entry` varchar(100) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;CREATE TABLE `finalTimes` ( `id` int(11) NOT NULL AUTO_INCREMENT,`contestant` int(11) DEFAULT NULL,`time` int(11) DEFAULT NULL,PRIMARY KEY (`id`), KEY `contestant` (`contestant`), CONSTRAINT `finaltimes_ibfk_1` FOREIGN KEY (`contestant`) REFERENCES `contestants` (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;CREATE TABLE `heatTimes` (`id` int(11) NOT NULL AUTO_INCREMENT,`contestant` int(11) DEFAULT NULL,`time` int(11) DEFAULT NULL,PRIMARY KEY (`id`),CONSTRAINT `heattimes_ibfk_1` FOREIGN KEY (`id`) REFERENCES `contestants` (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;";
public static void createTables(){
try {
PreparedStatement ps = conn.prepareStatement(tablesSQL);
ps.executeUpdate();
System.out.println("Tables Created");
} catch (SQLException e) {
e.printStackTrace();
}
}
那么为什么我会收到此错误?我的创建表 SQL 直接来自 MYSQL 数据库的转储。我从 MYSQL 迁移过来,因为我的软件将在独立计算机上运行,并且我不想安装其他任何东西,这就是为什么 apache derby 是一个不错的选择。
编辑
这是我的小测试类(class):
public class testAddContestantMethod {
public static void main(String[] args){
Contestant cont = new Contestant("Dean","Chester","Mazey");
DatabaseManager.createTables();
cont.writeContestantToDatabase();
DatabaseManager.shutdownDatabase();
}
}
最佳答案
如果 getDatabaseConnection
中出现异常,您只需将其打印出来 - 这意味着当您尝试创建连接时很可能出现异常,从而留下 conn
为 null
,导致 createTables
中出现 NullPointerException
。
此外,您还没有显示任何实际调用 getDatabaseConnection
的内容。
我建议您让 getDatabaseConnection
传播异常(如果有),然后从 createTables
调用它。
(一般来说,简单地打印出异常然后假装它没有发生不是合适的错误处理策略。)
关于java - 在 Derby 嵌入式模式下创建表时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6641344/