Search code examples
javamysqldatabasesqlexception

Why am I getting column not found in my SQL query?


I am trying to get data from my SQL database, but I get an error that says the 'Student_ID' Column doesn't exist although it does exist in the database.

Here is what I am doing:

public String[] getWeightedMarks(String s)
{
    int h = Integer.parseInt(s);

    String query = "SELECT md.Weighted_Marks FROM marks_details md " +
             "WHERE md.Student_ID = " + h;

    List<String> obj = new ArrayList<String>();

    try
    {
        ResultSet rs = stmt.executeQuery(query);

        while (rs.next())
        {
            obj.add((rs.getString("Weighted_Marks")).toString());
        }
    }
    catch(SQLException e)
    {
        System.out.println("Problem in Query");
        e.printStackTrace();
    }

    String[] a = (String[]) obj.toArray(new String[obj.size()]);

    return a;
}

Here is the error I am getting:

Problem in Query
java.sql.SQLException: Column 'Student_ID' not found.

Here is the screenshot of my Database and I am connected to this db:

enter image description here


Solution

  • It looks like your code is having trouble parsing the query for a reason that isn't immediately clear. Instead, you should use a PreparedStatement, e.g.

    PreparedStatement statement = connection.prepareStatement(
                 "SELECT md.Weighted_Marks FROM marks_details md WHERE md.Student_ID = ?";
    statement.setInt(1, h);
    ResultSet rs = statement.executeQuery();
    

    This should help mitigate any potential SQL injections and syntax errors.