获取MySQLSyntaxErrorException?

时间:2012-03-26 06:31:31

标签: java mysql jsp

我有这段代码:

    String check="SELECT COUNT(*) as check FROM recordstudent WHERE STUDENT_ID="+T_STUDENT_ID+" AND COURSE_ID="+T_COURSE_ID+" AND PACKAGE_ID="+T_PACKAGE_ID+" AND ACTIVITY_ID="+T_ACTIVITY_ID+" AND DATE="+T_DATE+ ";";
    rs=myStmt.executeQuery(check);
    int ch=0;

    while(rs.next()){

        ch=Integer.parseInt(rs.getString("check"));
    }

    if(ch==0)
    {

        String insertRecord="insert into recordstudent"+
                "(STUDENT_ID,COURSE_ID,PACKAGE_ID,ACTIVITY_ID,TEST_NAME,DATE,SCORE,TOTAL_MARKS,PERCENTAGE,CORRECT_ANSWER,TOTAL_QUESTIONS,STUDENT_NAME,SCORE_PER_DIVISION,ATTEMPTS)"+
                "VALUES("+
                "'"+T_STUDENT_ID+"',"+
                "'"+T_COURSE_ID+"',"+
                "'"+T_PACKAGE_ID+"',"+
                "'"+T_ACTIVITY_ID+"',"+
                "'"+T_TEST_NAME+"',"+
                "'"+T_DATE+"',"+
                "'"+T_SCORE+"',"+
                "'"+T_TOTAL_MARKS+"',"+
                "'"+T_PERCENTAGE+"',"+
                "'"+T_CORRECT_ANSWERS+"',"+
                "'"+T_TOTAL_QUESTIONS+"',"+
                "'"+T_STUDENT_NAME+"',"+
                "'"+T_SCORE_PER_DIVISION+"',"+
                "'"+t+"'"
                +");";

                myStmt.execute(insertRecord);



    }

只有当ch = 0时,此代码段才会在数据库中插入数据。但是我收到此错误:

      com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 
          You have an error in your SQL syntax; check the manual that corresponds 
          to your MySQL server version for the right syntax to use near 
          'check FROM recordstudent WHERE STUDENT_ID=11 AND COURSE_ID=2 AND PACKAGE_ID=11 A' 
          at line 1 

任何人都可以帮助我并解决我的问题吗?

3 个答案:

答案 0 :(得分:3)

从根本上说:不要以这种方式构建SQL。我注意到你已经在“插入”SQL语句中的值中引用了引号 - 但不是在“select”中。这是问题的开始 - 但你不应该在SQL中包含这样的值。您应该通过PreparedStatement使用参数化SQL ,并为参数设置值。优点:

  • 您可以更轻松地查看实际的SQL,因此您将能够发现语法错误。 (这基本上是将代码与数据分开。)
  • 非常重要)您不会对SQL injection attacks
  • 开放
  • 您无需担心数字,日期和时间等转换问题。

SQL中存在其他问题(例如空格和check是MySQL中的reserved word),但首先是你应该修复的是如何使用值。在您完成此操作之前,您的代码邀请安全问题。

(然后你应该开始使用比T_STUDENT_NAME等更常规的变量名,但这是另一回事。)

答案 1 :(得分:2)

check是保留字。用反引号围绕它:`check`

答案 2 :(得分:1)

试试这个

SELECT COUNT(*) as 'check' FROM recordstudent....

而不是

SELECT COUNT(*) as check FROM recordstudent....

我认为支票是关键字