我正在为我的第一个学校数据库项目工作。我以为自己很顺利,但遇到了一个空指针异常,我不知道如何在我所处的情况下修复它。分配是打开并读取一个访问数据库,然后拉来自它的信息,以找到最小余额的客户。
package dbproject;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MyFirstDB {
public static void main(String[] args)
{
ResultSet resultSet = null;
double totalPref = 0.0;
double lowestBalPref = 1000000;
String lowestBalCust = null;
double highestBalPref = 0.0;
String highestBalCust = null;
double totalBalance = 0.0;
ResultSet rs = null;
String convertTo = "";
double result = 0.0;
long lngCN = 0;
String query = null;
String url = "jdbc:ucanaccess://c:/cps/ms121.accdb";
try{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection con = DriverManager.getConnection(url);
if(con!=null){
System.out.println("Connecton Successful!");
}
else{
System.out.println("Connection Unsuccesful!");
System.exit(0);
}
Statement statement = con.createStatement();
if(statement != null)
System.out.println("Statement is not null");
resultSet = statement.executeQuery("SELECT * FROM CUSTOMER where preferred = 'y'");
while(resultSet.next()){
// System.out.println(resultSet.getString("CustomerName"));
totalPref = totalPref + 1;
if(rs.getDouble("Balance") < lowestBalPref){
lowestBalCust = rs.getString("CustomerName");
// System.out.println(resultSet.getDouble("Balance"));
}
}
System.out.println("Total Preferred Customers is " + totalPref);
System.out.println("The Customer with the lowest balance is " + lowestBalCust);
if (con != null)
con.close();
}catch (Exception e)
{
e.printStackTrace();
}
}
}
这些行特别是导致错误:
if(rs.getDouble("Balance") < lowestBalPref){
lowestBalCust = rs.getString("CustomerName");
答案 0 :(得分:0)
在这一行
System.out.println(&#34;余额最低的客户是&#34; + lowestBalCust);
您正在尝试打印lowestBalCust
属性,此属性以null开头:
String lowestBalCust = null;
如果此条件为false,您将获得空指针执行,因此,您必须在数据库中检查Balance
和CustomerName
的值是否存在
if(rs.getDouble("Balance") < lowestBalPref){
lowestBalCust = rs.getString("CustomerName");
}
最后...... rs = null
是...... null!所以将结果集置于变量
resultSet = statement.executeQuery("SELECT * FROM CUSTOMER where preferred = 'y'");
while(resultSet.next()){
// System.out.println(resultSet.getString("CustomerName"));
totalPref = totalPref + 1;
if(resultSet .getDouble("Balance") < lowestBalPref){
lowestBalCust = resultSet .getString("CustomerName");
// System.out.println(resultSet.getDouble("Balance"));
}
}
System.out.println("Total Preferred Customers is " + totalPref);
System.out.println("The Customer with the lowest balance is " + lowestBalCust);