-1
public class d7Table extends JFrame {

    String dbName = "mydb";
    String bdUser = "root";
    String dbPassword = "2323";
    String dbUrl = "jdbc:mysql://localhost/mydb";
    Connection con = null;
    PreparedStatement stm = null;
    ResultSet res = null;
    public JTable table;

    public d7Table() {
        try {
            con = DriverManager.getConnection(dbUrl, bdUser, dbPassword);
            System.out.println("Connected to database successfully!");
            res = stm.executeQuery("select * from mytable");

            table = new JTable(myTableModel(res));
            JOptionPane.showMessageDialog(null, new JScrollPane(table));

        } catch (SQLException ex) {
            System.out.println("Could not connect to database");
        }

        add(new JScrollPane(table), BorderLayout.CENTER);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(800, 600);
        this.setLocation(300, 60);
        this.setVisible(true);

    }

    public static DefaultTableModel myTableModel(ResultSet rs) throws SQLException {
        ResultSetMetaData metadata = (ResultSetMetaData) rs.getMetaData();
        int columnsCount = metadata.getColumnCount();
        Vector<String> columnNames = new Vector<>();
        for (int i = 1; i < columnsCount; i++) {
            columnNames.add(metadata.getColumnName(i));
        }
        Vector<Object> data = new Vector<>();
        while (rs.next()) {
            Vector<Object> eachLine = new Vector<>();
            for (int i = 1; i < columnsCount; i++) {
                eachLine.add(rs.getObject(i));
            }
            data.add(eachLine);
        }
        return new DefaultTableModel(data, columnNames);

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new d7Table();
            }
        });
    }
}

我的错误:

Connected to database successfully!
 Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at JDBCtest.d7Table.<init>(d7Table.java:33)  // refer to res =stm.execute... Row
at JDBCtest.d7Table$1.run(d7Table.java:73)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
...
4

2 回答 2

2

Statement在查询变量stm之前,您忘记在变量中获取 a 。使用此代码执行此操作:

stm = con.createStatement();
于 2013-07-19T22:42:19.313 回答
1

在这条线上

res = stm.executeQuery("select * from mytable");

stm变量仍然是null,导致您的NullPointerException. 你从来没有初始化它。

创建 a 的正确过程是PreparedStatement调用对象。prepareStatementConnection

但是你没有绑定变量;你只需要一个Statement在这里。声明stmStatement,并在连接后执行以下操作:

stm = con.createStatement();

然后你可以使用Statement你已经拥有这一行的查询:

res = stm.executeQuery("select * from mytable");
于 2013-07-19T22:40:18.253 回答