我现在想在程序启动时,在一个主类里头直接完成jdbc-odbc桥接,且只连接数据库一次
然后其他类中当要用到具体查询的时候,就另外生成 ResultSet rs可是现在确老是报这个错误:Hit uncaught exception java.lang.NullPointerException请指教...
然后其他类中当要用到具体查询的时候,就另外生成 ResultSet rs可是现在确老是报这个错误:Hit uncaught exception java.lang.NullPointerException请指教...
public class MainApp {
boolean packFrame = false;
String url="jdbc:odbc:kqsys";
String driver="sun.jdbc.odbc.JdbcOdbcDriver";
Connection con;
//Construct the application
public MainApp() {
MainFrame frame = new MainFrame();
//Validate frames that have preset sizes
//Pack frames that have useful preferred size info, e.g. from their layout
if (packFrame) {
frame.pack();
}
else {
frame.validate();
}
//Center the window
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
//*******************
//connect the database
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection(url,"sa","sa");
}
catch(Exception e){
System.out.println(" "+e);
}
} //Main method
public static void main(String[] args) { try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e) {
e.printStackTrace();
}
new MainApp(); }
}
public class MainFrame extends JFrame {
JPanel contentPane;
JMenuBar jMenuBar1 = new JMenuBar();
JMenu jMenuFile = new JMenu();
JMenuItem jMenuFileExit = new JMenuItem();
JMenu jMenuHelp = new JMenu();
JMenuItem jMenuHelpAbout = new JMenuItem();
JToolBar jToolBar = new JToolBar();
JButton jButton1 = new JButton();
JButton jButton2 = new JButton();
JButton jButton3 = new JButton();
ImageIcon image1;
ImageIcon image2;
ImageIcon image3;
JLabel statusBar = new JLabel();
JButton jButton4 = new JButton(); MainApp mp1;
//Construct the frame
public MainFrame() {
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
}
............
//**此处开始使用..
void jButton4_actionPerformed(ActionEvent e) {
if(e.getSource()==jButton4){
String sql="SELECT * FROM kqemp";
try {
Statement stmt=mp1.con.createStatement();
ResultSet rs=stmt.executeQuery("select * from kqemp");
while(rs.next()){
String ename=rs.getString(3);
System.out.println(" "+ename);}
rs.close();
}
catch(SQLException ee){System.out.println(" "+ee);} }
}
}.........
以下错误:
Statement stmt=mp1.con.createStatement();
public Connection getConnection()来取con
Statement stmt=mp1.getConnection().createStatement();
正如楼上所言,最好写个函数来返回 Connection 对象
看错误应该是你在某个可能发生异常的地方没有去捕获异常。