catch中的Java-MySQL-NullPointerException
我正在制作一个使用MySQL的bukkit插件,但是我在这段代码中不断得到一个空指针异常,我找不到有相同错误的人。我怎样才能消除这个错误 仅供参考,这是同一类中的connect方法:catch中的Java-MySQL-NullPointerException,java,mysql,bukkit,Java,Mysql,Bukkit,我正在制作一个使用MySQL的bukkit插件,但是我在这段代码中不断得到一个空指针异常,我找不到有相同错误的人。我怎样才能消除这个错误 仅供参考,这是同一类中的connect方法: public void connect() { try { Class.forName("com.mysql.jdbc.Driver"); stat = DriverManager.getConnection("jdbc:mysql://" + host + ":"
public void connect() {
try
{
Class.forName("com.mysql.jdbc.Driver");
stat = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + "?user=" + user + "&password=" + password).createStatement();
stat.execute("CREATE TABLE IF NOT EXISTS `tokens` (`Name` varchar(32),`amount` int)");
}
catch (ClassNotFoundException e) { e.printStackTrace(); }
catch (SQLException e) { e.printStackTrace(); }
}
给出错误的方法:
public void createAccount(String player) throws SQLException {
try
{
Scanner sc = new Scanner(player);
String name = sc.next();
String SQLText = "SELECT * FROM `tokens` WHERE name='" + name + "'";
ResultSet rs = stat.executeQuery(SQLText);
if (!rs.next())
{
// This code is not here yet
}
sc.close();
}
catch (Exception ex)
{
plugin.log.info("There is something wrong in the MySQLHandler: " + ex.toString()); // This gives me the nullpointerexception
}
}
使用全局语句字段
stat
,您不能以这种方式工作
应该关闭连接、语句和结果集
查看示例,最好是PreparedStatement,并尝试使用参考资料
用户和密码也可以作为单独的参数给出
try (PreparedStatemen stat = connection.prepareStatement(
"SELECT 1 FROM tokens WHERE name=? LIMIT 1")) {
stat.setString(1, name);
try (ResultSet rs = stat.executeQuery()) {
if (!rs.next()) {
return "Not found";
}
}
}
上面的stat
和rs
关闭,即使返回
准备好的语句不需要将单引号放在SQL字符串中,也不需要转义单引号、反斜杠等。此外,还可以防止SQL注入、恶意输入。当您有抛出NPE的行时
plugin.log.info("There is something wrong in the MySQLHandler: " + ex.toString()); // This gives me the nullpointerexception
以下变量可以为null:
- 插件
- plugin.log
- ex(这不应该发生,因为caucht异常不为null!)
提供堆栈可能很好。。尽管如此,我认为只要检查一下
plugin==null
,可能会让你走上正确的道路。如果没有堆栈跟踪很难说,但是plugin
很可能是null
谢谢!这肯定会有帮助
} catch (...)
if (plugin == null) System.out.println("plugin is null");
if (plugin.log == null) System.out.println("plugin.log is null");
//...
}