A Java-Library to build SQL-Statements
<dependency>
<groupId>de.jaggl.sqlbuilder</groupId>
<artifactId>sqlbuilder-core</artifactId>
<version>2.7.2</version>
</dependency>
private static final Table PERSONS = Table.create("persons");
private static final VarCharColumn FORENAME = PERSONS.varCharColumn("forename").size(50).build();
private static final VarCharColumn LASTNAME = PERSONS.varCharColumn("lastname").size(50).build();
public static final void main(String[] args)
{
Queries.select()
.from(PERSONS)
.where(LASTNAME.eq("Doe"))
.print();
}
This will output:
SELECT * FROM `persons` WHERE `persons`.`lastname` = 'Doe'
To get the SQL-statement as a string, call build()
instead of print()
Insert:
Queries.insertInto(PERSONS)
.set(FORENAME, "John")
.set(LASTNAME, "Doe")
.print();
INSERT INTO `persons` SET `persons`.`forename` = 'John', `persons`.`lastname` = 'Doe'
Update:
Queries.update(PERSONS)
.set(FORENAME, "John")
.where(LASTNAME.eq("Doe"))
.print();
UPDATE `persons` SET `persons`.`forename` = 'John', WHERE `persons`.`lastname` = 'Doe'
Delete:
Queries.deleteFrom(PERSONS)
.where(LASTNAME.eq("Doe"))
.print();
DELETE FROM `persons` WHERE `persons`.`lastname` = 'Doe'
Create table:
Queries.createTable(PERSONS).println()
CREATE TABLE `persons` (`forename` VARCHAR(50) DEFAULT NULL, `lastname` VARCHAR(50) DEFAULT NULL)
-
Build SQL-queries in different dialects, currently supported are:
- MySQL
- Sybase
-
Currently supported queries are:
- SELECT
- INSERT
- UPDATE
- DELETE
- CREATE TABLE
-
Type-safe query-building. Currently supported column-datatypes are:
- CHAR, VARCHAR, TEXT
- INT, BIGINT, MEDIUMINT, SMALLINT, TINYINT
- DOUBLE, FLOAT, DECIMAL
- DATE, DATETIME
-
Supports SQL-Functions, currently supported are:
- SUM
- MIN
- MAX
- AVG
- COUNT
- NOW
-
Build queries with or without indentation
By default the MySQL-dialect is chosen. To change the dialect, you can pass your wanted dialect to the print()
or build()
-method. The known dialects are collected in the Utility-Class Dialects
. Simple example for choose the known Sybase-dialect:
Queries.select()
.from(PERSONS)
.limit(100, 10)
.print(Dialects.SYBASE);
This will output:
SELECT TOP 100 START AT 11 * FROM `persons`
It is also possible to globally change the default-Dialect. To do so, set the system-property sqlbuilder.defaultDialect
to the name of the Dialect you want.
Just add Indentation.enabled()
to the print()
or build()
-method as follows:
Queries.select()
.from(PERSONS)
.where(LASTNAME.eq("Doe"))
.print(Indentation.enabled());
This will output:
SELECT
*
FROM
`persons`
WHERE `persons`.`lastname` = 'Doe'