Chang Yangshin
Chang Yangshin

Reputation: 11

access database cannot execute SQL LIKE

I am not able to query records from my database, and getting "UCAExc:::4.0.2 Invalid argument in JDBC call: parameter index out of range: 1" error message

How is this caused and how can I solve it?

    public void  query(){
    String name = name_tt.getText();
    DefaultTableModel model= new DefaultTableModel();
    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(0, 283, 555, 212);
    contentPane.add(scrollPane);

    table = new JTable(model);
    scrollPane.setViewportView(table);
    model.addColumn("ID");
    model.addColumn("IDs");
    model.addColumn("Name");
    try
    {
        PreparedStatement pst = con.prepareStatement("SELECT * FROM TEST 
        WHERE IDs LIKE '?*' ");
        pst.setString(1, name);
        ResultSet rs = pst.executeQuery();
        while(rs.next())
        {
            model.addRow(new Object[]{rs.getInt(1),rs.getString(2),rs.getInt(3)});
        }

    }
    catch(Exception e){
        System.out.println(e.getMessage());

    };

} 

Upvotes: 1

Views: 62

Answers (1)

Gord Thompson
Gord Thompson

Reputation: 123584

You need to do

PreparedStatement pst = con.prepareStatement("SELECT * FROM TEST WHERE IDs LIKE ?");
pst.setString(1, name + "*");
ResultSet rs = pst.executeQuery();

That way the parameter placeholder ? is part of the basic SQL statement, instead of being part of a string literal within the SQL statement.

Upvotes: 1

Related Questions