我正在尝试从我的前端 JSP 和另一个名为
questionpaper
的表向名为 questions
的表添加一些详细信息。
在表
questionpaper
中,我有一个名为 ExamID
的列,我必须向其中添加另一个名为 ExamId
的表中的 question
列的值。该 ExamId
值必须与从 JSP 页面添加的数据同时添加。来自 JSP 页面的数据正在添加,没有任何错误,但 ExamId
无法同时添加。
public int QuestionPaper(Questions paramQues) {
// TODO Auto-generated method stub
String query ="insert into questionpaper(Question,Opt1,Opt2,Opt3,Opt4,Answer,Marks,NegMarks,ExamId)values(?,?,?,?,?,?,?,?,?)";
int status=0;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/onlineexam", "root", "admin");
PreparedStatement stat1 = con.prepareStatement(query);
if((paramQues.getAns1()!=null)&&(paramQues.getAns2()!=null)&&(paramQues.getAns3()!=null)&&(paramQues.getAns4()!=null)&&(paramQues.getMarks()!=null)&&(paramQues.getNegM()!=null)&&(paramQues.getQues()!=null))
{
System.out.println("implementation "+paramQues.getOption());
System.out.println("Marks-->"+paramQues.getMarks());
System.out.println("Ans->>"+paramQues.getAns1());
stat1.setString(1,paramQues.getQues());
stat1.setString(2,paramQues.getAns1());
stat1.setString(3,paramQues.getAns2());
stat1.setString(4,paramQues.getAns3());
stat1.setString(5,paramQues.getAns4());
stat1.setString(6,paramQues.getOption());
stat1.setInt(7,paramQues.getMarks());
stat1.setInt(8,paramQues.getNegM());
System.out.println("Ans->>"+paramQues.getAns1());
String query2="SELECT * FROM questions ORDER BY ExamId DESC LIMIT 1";
PreparedStatement stat2 = con.prepareStatement(query2);
ResultSet rs1 = stat2.executeQuery(query2);
Integer Examid= rs1.getInt("ExamId");
System.out.println("exam id-->"+Examid);
stat1.setInt(9,Examid);
stat1.executeUpdate();
Integer TotalQues= rs1.getInt("TotalQuestions");
String query3="SELECT * FROM questionpaper ORDER BY PaperId DESC LIMIT 1";
PreparedStatement stat3 = con.prepareStatement(query3);
ResultSet rs2 = stat3.executeQuery(query3);
Integer PaperId= rs2.getInt("PaperId");
if(PaperId<=TotalQues)
status=1;
else
status=0;
}
}
catch (Exception e)
{
System.out.println("Exception in FacultyTry->" + e);
}
return status;
}
输出:
Answer:l
j
d
d
options-->o3
Marks-->2
NegMarks-->1
implementation o3
Marks-->2
Ans->>l
Ans->>l
Exception in FacultyTry->java.sql.SQLException
您已经提到,您的表包含
ExamID
列,并且您在 SQL 查询中使用 ExamId
。以下任一查询包含错误的列名称。
您的 SQL 查询:
String query ="insert into questionpaper(Question,Opt1,Opt2,Opt3,Opt4,Answer,Marks,
NegMarks,ExamId)values(?,?,?,?,?,?,?,?,?)";
OR
String query2="SELECT * FROM questions ORDER BY ExamId DESC LIMIT 1";
所需的 SQL 查询:
String query ="insert into questionpaper(Question,Opt1,Opt2,Opt3,Opt4,Answer,Marks,
NegMarks,ExamID)values(?,?,?,?,?,?,?,?,?)";
OR
String query2="SELECT * FROM questions ORDER BY ExamID DESC LIMIT 1";
在您的代码中,您不需要准备没有由
?
表示的参数的语句。
使用语句执行查询
ResultSet rs1 = stat1.executeQuery(query2);
或
Statement stat2 = con.createStatement();
ResultSet rs1 = stat2.executeQuery(query2);