我想從數據庫中檢索數據,然後在java中的表中顯示。下面是代碼示例,有人可以告訴我什麼是錯的,因爲當它運行時,我得到以下錯誤: java.lang.NullPointerException。從java中的數據庫檢索數據
package sample;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import net.proteanit.sql.DbUtils;
public class Table extends JFrame{
JTable table;
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
private void UpdateJTable(){
String sql = "select firstname, status from tblmember";
try{
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
private void conect(){
conn = myconnection.ConnectDb();
}
public Table(){
setLayout(new FlowLayout());
String [] columnName={"Name", "Status"};
Object [][] data={
{null, null},
{null, null}
};
table = new JTable(data, columnName);
table.setPreferredScrollableViewportSize(new Dimension(500,50));
table.setFillsViewportHeight(true);
JScrollPane sp = new JScrollPane(table);
add(sp);
}
public static void main(String[] args){
Table gui = new Table();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(700, 500);
gui.setVisible(true);
gui.setTitle("AAAAAAAA");
gui.UpdateJTable();
gui.conect();
}
}
我沒有看到任何你稱爲「connect()」的地方...所以我想這可能是爲什麼 – scartag 2012-02-04 20:00:38
在conn.prepareStatement(sql)之前調用connect(); – scartag 2012-02-04 20:01:15