Ryan
Ryan

Reputation: 49

SQL database query syntax error: "Encountered YEAR at line 1"

Whenever I run this query, I get Syntax error saying "Encountered "YEAR" at line 1. My column name is YEAR and for some reason it won't run, although all the other columns work fine.

public void getYears() {

    try {
        Class.forName("org.apache.derby.jdbc.ClientDriver");
        Connection conn = DriverManager.getConnection(url,user,pWord);
        Statement st = conn.createStatement();
        rs = st.executeQuery("SELECT YEAR FROM VEHICLES");
        while(rs.next()) {
            jComboBox1.addItem(rs.getString("YEAR"));
        }
        conn.close();

    } catch (SQLException | ClassNotFoundException ex) {
        Logger.getLogger(VehicleSearch.class.getName()).log(Level.SEVERE, null, ex);
    }
}

I have the same code for my other columns and they work fine when running, the YEAR column in a VARCHAR(15)

Upvotes: 2

Views: 1469

Answers (2)

user7334954
user7334954

Reputation: 15

You can use the single quote ( ' ) for this:

rs = st.executeQuery("SELECT 'YEAR' FROM VEHICLES");

Upvotes: 0

Mureinik
Mureinik

Reputation: 311843

"Year" is a reserved word in Apache Derby. In order to use it as a column name, you must escape it by surrounding it with double quotes ("):

rs = st.executeQuery("SELECT \"YEAR\" FROM VEHICLES");
// Here ---------------------^-----^

Upvotes: 4

Related Questions