我在从我创建的数据库中检索数据时遇到问题,条件是用户输入的数据将取决于他们键入“A”时输入的EmployeeCode(A,B或C)作为他们的代码,他们的数据输入应该进入数据库A,所以我在mysql上为不同的代码(A,B,C)创建了三个数据库。问题是InsertRecord()运行良好,因为用户的数据输入将转到正确的数据库,它应该去,但GetAllRecords()不起作用。
private String sqlInsert(){
if(employeeCode.equals("A")){
return "insert into MachineProblem2A(EmployeeName, EmployeeCode, EmployeeSales, EmployeeGross, EmployeeCommission, EmployeeResult)"+ "values(?,?,?,?,?,?)";
}else if(employeeCode.equals("B")){
return "insert into MachineProblem2B(EmployeeName, EmployeeCode, EmployeeSales, EmployeeGross, EmployeeCommission, EmployeeResult)"+ "values(?,?,?,?,?,?)";
}else if(employeeCode.equals("C")){
return "insert into MachineProblem2C(EmployeeName, EmployeeCode, EmployeeSales, EmployeeGross, EmployeeCommission, EmployeeResult)"+ "values(?,?,?,?,?,?)";
} return null;
}
private void insertRecord(Connection conn){
try{
PreparedStatement pstmnt= conn.prepareStatement(sqlInsert());
pstmnt.setString(1, employeeName);
pstmnt.setString(2, employeeCode);
pstmnt.setDouble(3, employeeSales);
pstmnt.setDouble(4, gross);
pstmnt.setDouble(5, commission);
pstmnt.setDouble(6, result);
//now commit to database
pstmnt.executeUpdate();
}catch(SQLException sqle){
sqle.printStackTrace();
}
}
insertRecord()运行良好,因为每当用户输入数据时,无论是MachineProblem2A,B还是C,它都会通过正确的数据库。
但是在我的GetAllRecords()上,我总是收到空指针异常错误。我不知道出了什么问题,因为我创建的函数sqlInsert正在工作,它类似于sqlRetrieve,但它不起作用。
private String sqlRetrieve(){
if(employeeCode.equals("A")){
return "select*from MachineProblem2A";
}else if(employeeCode.equals("B")){
return "select*from MachineProblem2B";
}else if(employeeCode.equals("C")){
return "select*from MachineProblem2C";
else return null;
}
public ResultSet getAllRecords(Connection conn){
ResultSet records = null;
try{
String sql=sqlRetrieve();
PreparedStatement pstmnt= conn.prepareStatement(sql);
records= pstmnt.executeQuery();
}catch(SQLException sqle){
sqle.printStackTrace();
}
return records;
}
**编辑**
每当我在GetAllRecords上使用employeeCode时,它是怎么来的? 我试图声明一个字符串并将其连接到我准备好的语句并且它工作,但调用employeeCode给我null。
String Try="A";
// get records
public ResultSet getAllRecords(Connection conn){
ResultSet records = null;
try{
PreparedStatement pstmnt= conn.prepareStatement("select * from MachineProblem2".concat(Try));
//IF I TRIED USING "select * from MachineProblem2".concat(employeeCode) or +employeeCode it won't work. //
records= pstmnt.executeQuery();
}catch(SQLException sqle){
sqle.printStackTrace();
}
return records;
}
但完全适用于我创建的其他函数,包括insertRecord
public void computeGross(){
switch(employeeCode){
case "A":
setGross(grossA+(getEmployeeSales()*grossSalesA));
break;
case "B":
setGross(grossB+(getEmployeeSales()*grossSalesB));
break;
case "C":
setGross(grossC+(getEmployeeSales()*grossSalesC));
break;
}
}