我正在使用MS Access .mdb作为我的数据库。我真的不明白这段代码,我从讲座中得到了它的副本。
多年前我使用过这段代码而且它曾经工作过,现在我遇到了一个错误,我不知道为什么。怎么了?
public class Connect {
public ResultSet rs;
Connection con;
java.sql.Statement st;
ResultSetMetaData rsm;
public Connect(){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=Db.mdb";
con = DriverManager.getConnection(url,"","");
st = con.createStatement(1004,1008);
} catch (Exception e){
}
}
public ResultSet selectData(String query){
ResultSet rset;
try {
rs = st.executeQuery(query);
rsm = rs.getMetaData();
if(rs.next()){
return rs;
}else{
return null;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
我正在使用Login类中的查询
if(con.selectData("select * from MsUser where Username='"+textUsername.getText()+"' and Password='"+textPassword.getText()+"'")==null){
JOptionPane.showMessageDialog(null, "Invalid username or password!", "Error", JOptionPane.ERROR_MESSAGE);
但它不起作用。
错误:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Connect.selectData(Connect.java:27)
at Login.actionPerformed(Login.java:98)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
答案 0 :(得分:0)
请确保表格" MsUser"是存在的。 你有没有实例化' con'来自' Connect'用于调用con.selectData()方法的类?
我认为你错过了实例化任何对象。