概述:尝试连接到 MS Access 数据库以将结果集返回到 jtable。
问题:java空指针异常
代码:
package sundata;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Database {
public String strMIGID;
public String strEBID;
public String strSUN;
public String[][] objIDList;
//CONNECTION INFO
private Connection con;
private String strDBCon="jdbc:ucanaccess://C:/Users/Luke/Documents/MainDB.mdb";
public String strEXMessage;
public int CreateConnection(){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(strDBCon);
return 1;
}catch(Exception ex){
ex.printStackTrace();
strEXMessage=ex.getMessage();
return 2;
}
}
public int CloseConnection(){
try{
con.close();
return 1;
}catch(Exception ex){
ex.printStackTrace();
strEXMessage=ex.getMessage();
return 2;
}
}
public int GetMIGIDRecord(String strMIGIDRef){
try{
System.out.println("Connecting to database using MIGID");
String strSQLString = "Select * from tblSuppliersData where Supplier1 = ?";
PreparedStatement preStatement = con.prepareStatement(strSQLString, ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
//SETTING FIRST CONDITION OF PREPARED STATEMENT IE ?
preStatement.setString(1, strMIGIDRef);
//EXECUTE QUERY
preStatement.executeQuery();
//RETURNS QUERY RESULTS INTO RESULT SET
ResultSet rs = preStatement.getResultSet();
//CHECK TO MAKE SURE SOME RECORDS ARE RETURNED
rs.last();
//IF CHECKS TO MAKE SURE RECORDS
if(rs.getRow()==0){
rs.close();
preStatement.close();
return 3;
}
//RECORDS NUMBER OF RECORDS
int iNoRecords = rs.getRow();
//CREATING 2D ARRAY WITH NO RECORDS (ROWS) AND TWO COLUMNS
String strTempdata[][] = new String [iNoRecords][3];
//MOVES BACK TO BEFORE FIRST RECORD
rs.beforeFirst();
//TRANSPOSES RS IN TO ARRAY
int i = 0;
while (rs.next()){
strTempdata[i][0]= rs.getString("MIGID");
strTempdata[i][1]= rs.getString("EBID");
strTempdata[i][2]= rs.getString("SUN");
i++;
}
objIDList = strTempdata;
//CLOSES CONNECTIONS
rs.close();
preStatement.close();
System.out.println("Connection complete");
return 1;
}catch(Exception ex){
ex.printStackTrace();
strEXMessage=ex.getMessage();
return 2;
}
}
我有一个表格,可以抓取 strMIGIDREF,如果需要,我可以粘贴代码,但我认为这不是问题所在。
这是我得到的错误,我已经粘贴了第一位,如果需要可以粘贴更多。
Connecting to database using MIGID
java.lang.NullPointerException
at sundata.Database.GetMIGIDRecord(Database.java:63)
at sundata.MainForm.MIGIDSearch(MainForm.java:141)
at sundata.MainForm.jmenuMIGIDSearchActionPerformed(MainForm.java:337)
at sundata.MainForm.access$000(MainForm.java:6)
at sundata.MainForm$1.actionPerformed(MainForm.java:58)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
第 63 行是
//CHECK TO MAKE SURE SOME RECORDS ARE RETURNED
rs.last();
我已经尝试了一些我在谷歌上找到的解决方案,但到目前为止还没有任何乐趣。我已经尝试了一段代码来检查连接等,并且似乎工作正常,只是当我尝试使用preparedstatement时它似乎错过了。结果集 rs = preStatement.getResultSet(); 只是一直说它的值为空,getMaxRows 也是如此。
我正在使用 Netbeans IDE 7.4 和 JAVA SE SDK 7