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)
...