Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 260
Dmitry Kach Avatar asked Sep 25 '16 15:09

Dmitry Kach


2 Answers

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')
like image 69
Dmitry Kach Avatar answered Sep 29 '22 06:09

Dmitry Kach


BinaryCondition.like() takes Object which is a Column Object and then it is converted to SqlObject using Converter.toColumnSqlObject(Object) internally . There is a method named findColumn(String columnName) and findSchema(String tableName) in Class DbTable and Class DbSchemarespectively where you can pass a simple String Object. Try this it would solve your problem:

 DbTable table1= schema.findSchema("table1");
 DbColumn column1 = table1.findColumn("column1");

 SelectQuery sql = new SelectQuery();
 sql.addAllColumns().addCustomFromTable(table1);
 sql.addCondition(BinaryCondition.like(column1, "A"));
like image 31
Shaggy Avatar answered Sep 29 '22 07:09

Shaggy