javasqlsqlbuilder

How to build SELECT query with sqlbuilder?


I am using Java and SQLBuilder from http://openhms.sourceforge.net/sqlbuilder/ and am trying to build SQL SELECT query dynamicly:

SelectQuery sql = new SelectQuery();
sql.addAllColumns().addCustomFromTable("table1");
sql.addCondition(BinaryCondition.like("column1", "A"));

However, it creates string like this:

SELECT * FROM table1 WHERE ('column1' LIKE 'A')

Because of wrong quotes ('column1') it doesn't work properly. I suppose it expects some Column object in .like() method. Is there any way to create query with proper quotes?


Solution

  • I've found a solution. I had to create new class Column that extends CustomSql and pass my column name as parameter:

    public class Column extends CustomSql {
       public Column(String str) {
          super(str);
       }
    }
    

    And then:

    SelectQuery sql = new SelectQuery();
    sql.addAllColumns().addCustomFromTable("table1");
    sql.addCondition(BinaryCondition.like(new Column("column1"), "A"));
    

    Or without creating own class:

    SelectQuery sql = new SelectQuery();
    sql.addAllColumns().addCustomFromTable("table1");
    sql.addCondition(BinaryCondition.like(new CustomSql("column1"), "A"));
    

    It creates following SQL query, which works fine:

    SELECT * FROM table1 WHERE (column1 LIKE 'A')