启动应用程序时会出现以下错误:
java.lang.NullPointerException
at me.MyApp.MyApp.Database.getConn(Database.java:30) ~[?:?]
at me.MyApp.MyApp.Models.MyAppModel.<init>(MyAppModel.java:18) ~[?:?]下面是如何设置数据库类:
public class Database {
private static MyApp instance = MyApp.getInstance();
private static Config config = new Config();
private static HikariDataSource ds = new HikariDataSource();
static {
HikariConfig dbConfig = new HikariConfig();
dbConfig.setJdbcUrl("jdbc:mysql://localhost:3306/" + config.get("database.database"));
dbConfig.setUsername(config.get("database.username"));
dbConfig.setPassword(config.get("database.password"));
dbConfig.setDriverClassName("com.mysql.jdbc.Driver");
dbConfig.addDataSourceProperty("cachePrepStmts", "true");
dbConfig.addDataSourceProperty("prepStmtCacheSize", "250");
dbConfig.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
}
public static Connection getConn() {
try {
return ds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}下面是触发错误的模型类:
public class MyAppModel {
private MyApp instance = MyApp.getInstance();
private Connection connection;
public MyAppModel() {
connection = Database.getConn();
}
public void createTable() {
BukkitRunnable r = new BukkitRunnable() {
@Override
public void run() {
try {
String sql = "CREATE TABLE IF NOT EXISTS `myapp` ( " +
" `id` INT NOT NULL AUTO_INCREMENT ," +
"`uuid` VARCHAR(255) NOT NULL ," +
" `join_message` VARCHAR(255) NOT NULL ," +
" `quit_message` VARCHAR(255) NOT NULL ," +
" `change_points` INT NOT NULL," +
" `last_modified` TIMESTAMP NOT NULL," +
" PRIMARY KEY (`id`)" +
")";
Statement statement = connection.createStatement();
statement.executeUpdate(sql);
} catch(SQLException e) {
e.printStackTrace();
}
}
};
r.runTaskAsynchronously(instance);
}
}我认为MyAppModel连接返回null,而我处理的TryCatch处理错误,但我不完全确定它为什么要返回null。我做错了什么?
我理解NullPointerException的概念,但不理解为什么我的应用程序会给我这个错误。
发布于 2017-06-08 15:51:55
在getConn()函数中调用ds.getConnection(),但是变量ds从未在类中创建。确保初始化名为ds的HikariDataSource对象。
对不起,我被正在使用的对象搞混了,所以将dbConfig更改为您所拥有的,然后根据javadocs -> HikariDataSource (HikariConfig configuration)使用它的构造函数创建新的对象。
因此,您需要切换对象的初始化,并在dbConfig对象的构造函数中使用您的HikariDataSource对象。
private static HikariConfig dbConfig;
static { //keep this the same
dbConfig = new HikariConfig();
dbConfig.setJdbcUrl("jdbc:mysql://localhost:3306/" + config.get("database.database"));
dbConfig.setUsername(config.get("database.username"));
dbConfig.setPassword(config.get("database.password"));
dbConfig.setDriverClassName("com.mysql.jdbc.Driver");
dbConfig.addDataSourceProperty("cachePrepStmts", "true");
dbConfig.addDataSourceProperty("prepStmtCacheSize", "250");
dbConfig.addDataSourceProperty( "prepStmtCacheSqlLimit", "2048");
}
private static HikariDataSource ds = new HikariDataSource(dbConfig); //intialize here with your newly created HikariConfig objecthttps://stackoverflow.com/questions/44440180
复制相似问题