Search code examples
javasqlsql-serverms-accessms-access-2007

Select a specific value in Access using SQL


I am working on a project that links Access to a Java GUI. I am currently looking for a way to select a record, in a query, that contains a specific value.

If my fields are:

Name |      Job      | Hours Worked
Tom  | Sales Support |       6
Bill |    Manager    |       8
Tom  |  Sales Floor  |       5

and I enter Tom in a search field in the GUI, I would like it to return the following to the GUI:

Name |      Job      | Hours Worked
Tom  | Sales Support |       6
Tom  |  Sales Floor  |       5

I tried using this code:

       ArrayList<String> list = new ArrayList<>();
       String filePath = "C:\\Users\\Bob\\Schedule.accdb";
       Connection con=DriverManager.getConnection("jdbc:ucanaccess://"+filePath);
       Statement st = con.createStatement();
       ResultSet rs = st.executeQuery("SELECT * FROM [Double Booking] WHERE [Name] = Tom");
       while(rs.next()) list.add(rs.getString(1));
       con.close();
       return list.toArray();

but I get the error:

net.ucanaccess.jdbc.UcanaccessSQLException: user lacks privilege or object not found: TOM

When I enter st.executeQuery("SELECT [Name] FROM [Double Booking]") I get a similar error:

net.ucanaccess.jdbc.UcanaccessSQLException: user lacks privilege or object not found: DOUBLE BOOKING

Solution

  • Since Tom is intended to be a string literal, you need to add quote characters:

    "SELECT * FROM [Double Booking] WHERE [Name] = 'Tom'"
    

    That said, if 'Tom' is just an example, it would be better to use a parameterised query if possible.