java.lang.NullPointerException:无法调用“java.sql.Statement.executeQuery(String)”,因为“<local2>”为空

时间:2021-07-14 10:23:20

标签: java sql jdbc nullpointerexception

我正在学习 Java 并且遇到了这个错误。我认为 Statement stmt = null 导致了错误。任何帮助将不胜感激。

这是我写的代码:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

class Database {
    public static void main(String args[]) {
        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
            System.out.println("DB CONNECTED!");
            conn.createStatement();
            String sql = "SELECT * FROM emp";
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                System.out.println("I am " + rs.getString("name") + " and i live in " + rs.getString("city")
                        + ". Btw i am " + rs.getInt("age") + " of age.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            // System.out.println("Error: " + e.toString());
        }
    }
}

我遇到的错误:

java.lang.NullPointerException: Cannot invoke "java.sql.Statement.executeQuery(String)" because "<local2>" is null
        at Database.main(db.java:16)

1 个答案:

答案 0 :(得分:1)

你需要使用 stmt = conn.createStatement(); 来初始化它

class Database {
    public static void main(String args[]) {
        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
            System.out.println("DB CONNECTED!");
            stmt = conn.createStatement();
            String sql = "SELECT * FROM emp";
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                System.out.println("I am " + rs.getString("name") + " and i live in " + rs.getString("city")
                        + ". Btw i am " + rs.getInt("age") + " of age.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            // System.out.println("Error: " + e.toString());
        }
    }
}