Danny D
Danny D

Reputation: 33

Incorrect syntax near a keyword in my query

When i run my query in this method i get the following error:

Got an exception! Incorrect syntax near ';'.

NOTE that my courseNr is a VARCHAR in the DB.

I've tried to run the query in MSSQL and it works but not in java.

public ArrayList<Student> getAssignedStudents(Course course){
    try {
        Statement stmt = connection.createStatement();
        ResultSet rset = stmt.executeQuery("SELECT Student.pnr, Student.namn, Registrering.betyg FROM Registrering INNER JOIN Student ON Registrering.pnr = Student.pnr WHERE betyg != NULL AND kursnr = '" + course.getCourseNr() + "';");

        ArrayList<Student> studentList = new ArrayList<Student>();
        while (rset.next()) {

            String pnr = rset.getString("pnr");
            String name = rset.getString("namn");
            String grade = rset.getString("betyg");

            Student student = new Student();
            student.setName(name);
            student.setPnr(pnr);
            student.setGrade(grade);

            studentList.add(student);

        }
        return studentList;
    } catch (Exception e) {
        System.err.println("Got an exception! ");
        System.err.println(e.getMessage());
        return null;
    }
}

Upvotes: 2

Views: 649

Answers (2)

Hisham Maudarbocus
Hisham Maudarbocus

Reputation: 620

It might be your kursnr is an INT field in you db. If so you should remove the single quotes ' and ' and hopefully you'll be good to go

Upvotes: 0

peter.petrov
peter.petrov

Reputation: 39477

Try doing (betyg is not NULL) instead of what you're doing.
Also, make sure the value of course.getCourseNr() does not contain an apostrophe (').

Upvotes: 1

Related Questions