### Example: Using bind with a POJO Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/query.md Demonstrates how to use bind to map POJO properties to query parameters. ```java class UserFilter { public String name; public boolean active; // getters optional if fields are public } UserFilter filter = new UserFilter(); filter.name = "Alice"; filter.active = true; con.createQuery("SELECT * FROM users WHERE name = :name AND active = :active") .bind(filter) .executeAndFetch(User.class); ``` -------------------------------- ### getSql2o() Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/connection.md Gets the parent Sql2o instance. ```APIDOC ## getSql2o() ### Description Gets the parent Sql2o instance. ### Returns: The parent `Sql2o` instance ``` -------------------------------- ### Enum Conversion Example Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/converters.md This example shows how SQL2O automatically handles Enum conversions to and from the database. By default, enums are stored as VARCHAR using their constant names. ```java enum Status { ACTIVE, INACTIVE, PENDING } class User { public int id; public String name; public Status status; // stored as VARCHAR "ACTIVE" by default } // Insert User user = new User(); user.id = 1; user.name = "John"; user.status = Status.ACTIVE; con.createQuery("INSERT INTO users (id, name, status) VALUES (:id, :name, :status)") .bind(user) .executeUpdate(); // Select User fetched = con.createQuery("SELECT * FROM users WHERE id = :id") .addParameter("id", 1) .executeAndFetchFirst(User.class); // fetched.status == Status.ACTIVE ``` -------------------------------- ### Basic Sql2o Database Interaction Example Source: https://github.com/aaberg/sql2o/blob/master/README.md Demonstrates setting up a Sql2o connection, creating a table, inserting data, and fetching a user object. Ensure you have the appropriate JDBC driver for your database. ```java import org.sql2o.*; public class Main { public static void main(String[] args) { String url = "jdbc:h2:mem:test"; // Example using H2 in-memory database try (Sql2o sql2o = new Sql2o(url, "username", "password"); Connection con = sql2o.open()) { con.createQuery("CREATE TABLE users (id INTEGER PRIMARY KEY, name VARCHAR(50))").executeUpdate(); con.createQuery("INSERT INTO users (id, name) VALUES (:id, :name)") .addParameter("id", 1) .addParameter("name", "Alice") .executeUpdate(); User user = con.createQuery("SELECT * FROM users WHERE id = :id") .addParameter("id", 1) .executeAndFetchFirst(User.class); System.out.println("User: " + user.name); } } } class User { public int id; public String name; } ``` -------------------------------- ### getKeys() Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/connection.md Gets all generated keys from the last `executeUpdate()` call. ```APIDOC ## getKeys() ### Description Gets all generated keys from the last `executeUpdate()` call. ### Returns: Array of generated keys, or `null` if none were generated ### Throws: `Sql2oException` if `returnGeneratedKeys` was not enabled ``` -------------------------------- ### Implement Custom ConnectionSource Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/advanced.md Implement the ConnectionSource interface for custom connection pooling or routing logic. This example shows a routed source based on a key. ```java import org.sql2o.connectionsources.ConnectionSource; public class RoutedConnectionSource implements ConnectionSource { private final Map dataSources; private final String defaultKey; public RoutedConnectionSource(Map dataSources, String defaultKey) { this.dataSources = dataSources; this.defaultKey = defaultKey; } @Override public java.sql.Connection getConnection() throws SQLException { // Route to appropriate DataSource based on current context String key = ThreadLocal-based routing or other logic; DataSource ds = dataSources.getOrDefault(key, dataSources.get(defaultKey)); return ds.getConnection(); } } ``` -------------------------------- ### getKey() Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/connection.md Gets the first generated key from the last `executeUpdate()` call. ```APIDOC ## getKey() ### Description Gets the first generated key from the last `executeUpdate()` call. ### Returns: The generated key, or `null` if none was generated ### Throws: `Sql2oException` if `returnGeneratedKeys` was not enabled ### Example: ```java con.createQuery("INSERT INTO users (name) VALUES (:name)", true) .addParameter("name", "John") .executeUpdate(); long userId = ((Number) con.getKey()).longValue(); ``` ``` -------------------------------- ### Begin Transaction with Alternative ConnectionSource and Isolation Level Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/sql2o-main.md Starts a transaction using an alternative ConnectionSource and specifies the SQL isolation level. This offers maximum flexibility in transaction management. ```java public Connection beginTransaction(ConnectionSource connectionSource, int isolationLevel) ``` -------------------------------- ### XML Configuration for DataSource and Sql2o Source: https://github.com/aaberg/sql2o/wiki/Documentation/Integration-with-Spring-Framework Configure a BasicDataSource and Sql2o bean using XML for Spring. This setup is suitable for basic Spring applications. ```xml com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/testDB user pass ``` -------------------------------- ### Validate Good POJO Structure Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/errors.md Example of a valid POJO for SQL2O mapping, demonstrating the requirement for a public no-arg constructor and public fields. ```java // Good POJO class User { public int id; // public field public String name; public User() {} // required: no-arg constructor } ``` -------------------------------- ### Initialize SQL2O as a Static Instance in DAO Source: https://github.com/aaberg/sql2o/wiki/Documentation/Configuration For web applications where a new DAO instance might be created per HTTP request, initializing SQL2O as a static variable in the DAO is preferred. This ensures the SQL2O instance is created only once when the application starts. ```java public class MyDao { private static Sql2o sql2o; static{ sql2o = new Sql2o("jdbc:mysql://localhost:3306/myDB", "myUsername", "topSecretPassword"); } } ``` -------------------------------- ### Get Table Structure with sql2o Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/quick-reference.md Fetches table structure and iterates through columns to print their names and types. Requires a database connection. ```java Table table = con.createQuery("SELECT * FROM users LIMIT 1") .executeAndFetchTable(); for (Column col : table.columns()) { System.out.println(col.getName() + ": " + col.getType()); } ``` -------------------------------- ### isRollbackOnClose() Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/connection.md Gets whether rollback on close is enabled. ```APIDOC ## isRollbackOnClose() ### Description Gets whether rollback on close is enabled. ### Returns: `true` if enabled, `false` otherwise ``` -------------------------------- ### Initialize SQL2O with Connection Details Source: https://github.com/aaberg/sql2o/wiki/Documentation/Configuration Use this constructor to establish a direct connection to your database by providing the JDBC URL, username, and password. ```java Sql2o sql2o = new Sql2o("jdbc:mysql://localhost:3306/myDB", "myUsername", "topSecretPassword"); ``` -------------------------------- ### Begin a Database Transaction Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/sql2o-main.md Starts a new database transaction with the default isolation level (TRANSACTION_READ_COMMITTED). The returned Connection must have commit() or rollback() called to finalize the transaction. ```java public Connection beginTransaction() ``` ```java Connection con = sql2o.beginTransaction(); try { con.createQuery("UPDATE users SET active = true WHERE id = :id") .addParameter("id", 1) .executeUpdate(); con.commit(); } catch (Exception e) { con.rollback(); } ``` -------------------------------- ### getBatchResult() Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/connection.md Gets the result of the last `executeBatch()` call. ```APIDOC ## getBatchResult() ### Description Gets the result of the last `executeBatch()` call. ### Returns: Array of row counts for each statement in the batch ### Throws: `Sql2oException` if `executeBatch()` was not called ``` -------------------------------- ### Initialize SQL2O with DataSource Source: https://github.com/aaberg/sql2o/wiki/Documentation/Configuration Alternatively, you can initialize SQL2O using an existing DataSource object. ```java Sql2o sql2o = new Sql2o(myDataSource); ``` -------------------------------- ### isRollbackOnException() Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/connection.md Gets whether automatic rollback on exception is enabled. ```APIDOC ## isRollbackOnException() ### Description Gets whether automatic rollback on exception is enabled. ### Returns: `true` if enabled, `false` otherwise ``` -------------------------------- ### Create and Open Sql2o Connection Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/quick-reference.md Instantiate Sql2o with your database connection string, username, and password. Then, open a connection using a try-with-resources statement for automatic closing. ```java Sql2o sql2o = new Sql2o("jdbc:h2:mem:test", "sa", ""); try (Connection con = sql2o.open()) { // use connection } ``` -------------------------------- ### Get First Generated Key as Type Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/connection.md Retrieves the first generated key and converts it to a specified Java type. Ensure the target type is compatible with the generated key. ```java public V getKey(Class returnType) Gets the first generated key converted to a specific type. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | returnType | Class | Yes | — | Type to convert the key to (e.g., `Long.class`, `String.class`) | **Returns:** The generated key converted to the specified type **Throws:** `Sql2oException` if key cannot be converted ``` -------------------------------- ### Chaining Query Configuration Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/connection.md Shows how to chain multiple configuration methods on a query object before execution, such as setting parameters and query options. ```java Query query = con.createQuery("SELECT * FROM users WHERE active = :active") .addParameter("active", true) .setCaseSensitive(false) .setAutoDeriveColumnNames(true); ``` -------------------------------- ### Custom Money Converter Implementation Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/interfaces.md Example implementation of the Converter interface for a custom 'Money' type. Handles conversion from various database types (String, BigDecimal, Number) to the Money object and converts Money objects back to BigDecimal for database storage. ```java // Custom converter for a Money type public class MoneyConverter implements Converter { @Override public Money convert(Object val) throws ConverterException { if (val == null) return null; try { if (val instanceof String) { return Money.parse((String) val); } else if (val instanceof BigDecimal) { return new Money((BigDecimal) val); } else if (val instanceof Number) { return new Money(new BigDecimal(val.toString())); } throw new ConverterException("Cannot convert " + val.getClass()); } catch (Exception e) { throw new ConverterException("Error converting to Money", e); } } @Override public Object toDatabaseParam(Money val) { if (val == null) return null; return val.getAmount(); // returns BigDecimal } } ``` -------------------------------- ### Get All Generated Keys as List Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/connection.md Retrieves all generated keys and converts them to a specified Java type, returning them as a List. Ensure the target type is compatible with the generated keys. ```java public List getKeys(Class returnType) Gets all generated keys converted to a specific type. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | returnType | Class | Yes | — | Type to convert keys to | **Returns:** List of generated keys converted to the specified type ``` -------------------------------- ### Get Table Rows Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Retrieves the list of rows from the table. ```java public List rows() ``` -------------------------------- ### Sql2o Main Entry Point Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/INDEX.md The primary `Sql2o` class serves as the main entry point for database connections, supporting initialization via JDBC URL, DataSource, or JNDI. It provides methods for managing connections, initiating explicit or automatic transactions, and configuring column mapping. ```APIDOC ## Sql2o Main Entry Point ### Description The `org.sql2o.Sql2o` class is the main entry point for interacting with the database. It handles the initialization of database connections and provides methods for transaction management and connection pooling. ### Key Classes - `org.sql2o.Sql2o` ### Key Methods - Constructors for JDBC URL, DataSource, and JNDI - `open()` - Open connections - `beginTransaction()` - Explicit transactions - `runInTransaction()` - Automatic transactions - `withConnection()` - Auto-closed connections - Connection source management - Column mapping configuration ``` -------------------------------- ### Execute Queries within a Transaction Source: https://github.com/aaberg/sql2o/wiki/Documentation/Transactions Use `beginTransaction()` to start a transaction and `commit()` to finalize it. Queries executed via the `Connection` object returned by `beginTransaction()` will be part of this transaction. The transaction is automatically rolled back if the try-with-resources block is exited without an explicit `commit()` or `rollback()`. ```java String sql1 = "INSERT INTO SomeTable(id, value) VALUES (:id, :value)"; String sql2 = "UPDATE SomeOtherTable SET value = :val WHERE id = :id"; try (Connection con = sql2o.beginTransaction()) { con.createQuery(sql1).addParameter("id", idVariable1).addParameter("val", valueVariable1).executeUpdate(); con.createQuery(sql2).addParameter("id", idVariable2).addParameter("val", valueVariable2).executeUpdate(); con.commit(); } ``` -------------------------------- ### Validate Acceptable POJO Structure with Getters/Setters Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/errors.md Example of an acceptable POJO structure using bean-style getters and setters, along with the required public no-arg constructor. ```java // Also acceptable class Product { private int id; private String name; public Product() {} // required: no-arg constructor public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` -------------------------------- ### Create Sql2o with JDBC URL and Credentials Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/sql2o-main.md Create a Sql2o instance using a JDBC URL, username, and password. Sql2o automatically detects database-specific quirks from the URL. ```java public Sql2o(String url, String user, String pass) ``` ```java Sql2o sql2o = new Sql2o("jdbc:h2:mem:test", "sa", ""); try (Connection con = sql2o.open()) { con.createQuery("CREATE TABLE users (id INT, name VARCHAR(50))") .executeUpdate(); } ``` -------------------------------- ### Get Table Columns Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Retrieves the list of columns for the table. ```java public List columns() ``` -------------------------------- ### Begin Transaction with Isolation Level Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/sql2o-main.md Starts a new database transaction with a specified SQL isolation level. This method is useful when fine-grained control over transaction concurrency is required. ```java public Connection beginTransaction(int isolationLevel) ``` -------------------------------- ### Create Sql2o with DataSource Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/sql2o-main.md Initialize Sql2o using an existing DataSource. Sql2o will attempt to automatically detect database quirks from the provided DataSource. ```java public Sql2o(DataSource dataSource) ``` ```java HikariConfig config = new HikariConfig(); config.setJdbcUrl("jdbc:postgresql://localhost/mydb"); config.setUsername("user"); config.setPassword("pass"); HikariDataSource ds = new HikariDataSource(config); Sql2o sql2o = new Sql2o(ds); ``` -------------------------------- ### getJdbcConnection() Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/connection.md Gets the underlying JDBC Connection for advanced use cases. ```APIDOC ## getJdbcConnection() ### Description Gets the underlying JDBC Connection for advanced use cases. ### Returns: The raw `java.sql.Connection` instance ``` -------------------------------- ### Create Sql2o with JDBC URL, Credentials, and Quirks Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/sql2o-main.md Instantiate Sql2o with explicit JDBC connection details and a specific Quirks object for database-specific configurations. ```java public Sql2o(String url, String user, String pass, Quirks quirks) ``` -------------------------------- ### Get Column Name Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Retrieves the name of a result set column. ```java public String getName() ``` -------------------------------- ### Begin Transaction with Alternative ConnectionSource Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/sql2o-main.md Initiates a transaction using a provided alternative ConnectionSource. This allows for transactions to be managed independently of the default sql2o configuration. ```java public Connection beginTransaction(ConnectionSource connectionSource) ``` -------------------------------- ### Execute a Basic Query Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/README.md Fetches a list of users from the database using a simple SELECT statement. Ensure you have a User class defined and a 'users' table in your database. ```java try (Connection con = sql2o.open()) { List users = con.createQuery("SELECT * FROM users") .executeAndFetch(User.class); } ``` -------------------------------- ### throwIfNull Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/converters.md Gets a converter for a given class, throwing a ConverterException if the converter is null. ```APIDOC ## throwIfNull(Class clazz, Converter converter) ### Description Gets a converter, throwing an exception if not found. ### Method Signature ```java public static Converter throwIfNull(Class clazz, Converter converter) throws ConverterException ``` ### Parameters #### Path Parameters - **clazz** (Class) - Required - Class to get converter for - **converter** (Converter) - Optional - Converter to check ### Throws - **ConverterException** - if converter is null ``` -------------------------------- ### Custom PooledConnectionSource Implementation Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/interfaces.md A sample implementation of ConnectionSource demonstrating a simple connection pool. It manages a queue of connections and creates new ones when the pool is empty. ```java // Custom connection source with a simple pool public class PooledConnectionSource implements ConnectionSource { private final Queue pool = new LinkedList<>(); private final String url; private final String user; private final String password; public PooledConnectionSource(String url, String user, String password) { this.url = url; this.user = user; this.password = password; } @Override public java.sql.Connection getConnection() throws SQLException { synchronized (pool) { if (!pool.isEmpty()) { java.sql.Connection conn = pool.poll(); if (!conn.isClosed()) { return conn; } } } // Create new connection if pool is empty return DriverManager.getConnection(url, user, password); } } ``` ```java // Usage ConnectionSource source = new PooledConnectionSource( "jdbc:mysql://localhost/mydb", "user", "pass" ); Sql2o sql2o = new Sql2o(source); ``` -------------------------------- ### getResult() Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/connection.md Gets the result of the last `executeUpdate()` call (number of rows affected). ```APIDOC ## getResult() ### Description Gets the result of the last `executeUpdate()` call (number of rows affected). ### Returns: Number of rows affected by the last update ### Throws: `Sql2oException` if `executeUpdate()` was not called ### Example: ```java con.createQuery("UPDATE users SET active = true") .executeUpdate(); int rowsUpdated = con.getResult(); ``` ``` -------------------------------- ### Get Column Index Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Retrieves the 0-based index of a result set column. ```java public Integer getIndex() ``` -------------------------------- ### Sql2o(String url, String user, String pass) Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/sql2o-main.md Creates a new Sql2o instance with direct JDBC connection details. The database quirks are automatically detected from the provided URL. ```APIDOC ## Sql2o(String url, String user, String pass) ### Description Creates a new Sql2o instance with JDBC connection details. Automatically detects database quirks from the URL. ### Parameters #### Path Parameters - **url** (String) - Required - JDBC database URL (with or without "jdbc:" prefix) - **user** (String) - Optional - Database username - **pass** (String) - Optional - Database password ### Throws - Sql2oException if connection cannot be established ### Example ```java Sql2o sql2o = new Sql2o("jdbc:h2:mem:test", "sa", ""); try (Connection con = sql2o.open()) { con.createQuery("CREATE TABLE users (id INT, name VARCHAR(50))") .executeUpdate(); } ``` ``` -------------------------------- ### isCaseSensitive Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/query.md Gets whether column name matching is currently set to be case-sensitive for this query. ```APIDOC ## isCaseSensitive() ### Description Gets whether column name matching is case-sensitive. ### Method GET ### Endpoint /query/isCaseSensitive ### Response #### Success Response (200) - **boolean** - `true` if case-sensitive, `false` otherwise ### Response Example { "boolean": true } ``` -------------------------------- ### ServiceLoader Configuration File Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/advanced.md Create a `META-INF/services/org.sql2o.converters.ConvertersProvider` file containing the fully qualified name of your `ConvertersProvider` implementation. This file should be placed in your JAR's `META-INF/services/` directory. ```plaintext com.example.CustomConvertersProvider ``` -------------------------------- ### Configure ServiceLoader for Custom Converters Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/converters.md Create a service provider configuration file in META-INF/services/org.sql2o.converters.ConvertersProvider. This file should contain the fully qualified class name of your custom ConvertersProvider implementation, allowing Sql2o to load it automatically. ```text com.example.MyConvertersProvider ``` -------------------------------- ### getKeys(Class returnType) Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/connection.md Gets all generated keys converted to a specific type. ```APIDOC ## getKeys(Class returnType) ### Description Gets all generated keys converted to a specific type. ### Parameters: #### Path Parameters - **returnType** (Class) - Required - Type to convert keys to ### Returns: List of generated keys converted to the specified type ``` -------------------------------- ### Set Up In-Memory H2 Database for Unit Tests Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/best-practices.md Initialize an in-memory H2 database for unit tests using a JDBC URL. Ensure tables are created before running tests that interact with them. ```java @Before public void setUp() { sql2o = new Sql2o("jdbc:h2:mem:test", "sa", ""); try (Connection con = sql2o.open()) { con.createQuery("CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(50))") .executeUpdate(); } } ``` -------------------------------- ### Get Parent Sql2o Instance Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/connection.md Retrieves the parent Sql2o object from which this Connection was opened. ```java public Sql2o getSql2o() Gets the parent Sql2o instance. **Returns:** The parent `Sql2o` instance ``` -------------------------------- ### getConverterIfExists Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/converters.md Gets a converter for a given class. Returns null if no converter is found for the specified class. ```APIDOC ## getConverterIfExists(Class clazz) ### Description Gets a converter for a class, returning null if not found. ### Method Signature ```java public static Converter getConverterIfExists(Class clazz) ``` ### Parameters #### Path Parameters - **clazz** (Class) - Required - Class to get converter for ``` -------------------------------- ### Integrate with Connection Pool (HikariCP) Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/quick-reference.md Configure HikariCP for connection pooling and initialize SQL2O with the data source. ```java HikariConfig config = new HikariConfig(); config.setJdbcUrl("jdbc:postgresql://localhost/mydb"); config.setUsername("user"); config.setPassword("pass"); HikariDataSource ds = new HikariDataSource(config); Sql2o sql2o = new Sql2o(ds); ``` -------------------------------- ### getKey(Class returnType) Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/connection.md Gets the first generated key converted to a specific type. ```APIDOC ## getKey(Class returnType) ### Description Gets the first generated key converted to a specific type. ### Parameters: #### Path Parameters - **returnType** (Class) - Required - Type to convert the key to (e.g., `Long.class`, `String.class`) ### Returns: The generated key converted to the specified type ### Throws: `Sql2oException` if key cannot be converted ``` -------------------------------- ### Get LazyTable Rows Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Retrieves an iterable of rows from the lazy-loaded table. Rows are fetched on demand. ```java public Iterable rows() ``` -------------------------------- ### Sql2o(DataSource dataSource) Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/sql2o-main.md Creates a new Sql2o instance using a provided DataSource. Database quirks are automatically detected from the DataSource. ```APIDOC ## Sql2o(DataSource dataSource) ### Description Creates a new Sql2o instance using a DataSource. Automatically detects database quirks from the DataSource. ### Parameters #### Path Parameters - **dataSource** (DataSource) - Required - JDBC DataSource to use for connections ### Throws - Sql2oException if quirks detection fails ### Example ```java HikariConfig config = new HikariConfig(); config.setJdbcUrl("jdbc:postgresql://localhost/mydb"); config.setUsername("user"); config.setPassword("pass"); HikariDataSource ds = new HikariDataSource(config); Sql2o sql2o = new Sql2o(ds); ``` ``` -------------------------------- ### Get Column SQL Type Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Retrieves the SQL type name of a result set column. ```java public String getType() ``` -------------------------------- ### beginTransaction(ConnectionSource connectionSource) Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/sql2o-main.md Begins a transaction using an alternative ConnectionSource. This is useful when you need to manage connections from a different source within a transaction. ```APIDOC ## beginTransaction(ConnectionSource connectionSource) ### Description Begins a transaction using an alternative ConnectionSource. ### Method Not applicable (Java method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **connectionSource** (ConnectionSource) - Required - Alternative connection source implementation ### Response #### Success Response - **Connection** - A `Connection` instance in transaction mode ``` -------------------------------- ### Sql2o(String url, String user, String pass, Quirks quirks) Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/sql2o-main.md Creates a new Sql2o instance with JDBC connection details and explicit specification of database quirks. ```APIDOC ## Sql2o(String url, String user, String pass, Quirks quirks) ### Description Creates a new Sql2o instance with JDBC connection details and explicit Quirks specification. ### Parameters #### Path Parameters - **url** (String) - Required - JDBC database URL - **user** (String) - Optional - Database username - **pass** (String) - Optional - Database password - **quirks** (Quirks) - Required - Database-specific quirks and workarounds ### Throws - Sql2oException if connection cannot be established ``` -------------------------------- ### isThrowOnMappingFailure Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/query.md Gets whether the query is configured to throw an exception upon encountering a column-to-property mapping failure. ```APIDOC ## isThrowOnMappingFailure() ### Description Gets whether mapping failures throw exceptions. ### Method GET ### Endpoint /query/isThrowOnMappingFailure ### Response #### Success Response (200) - **boolean** - `true` if exceptions are thrown, `false` otherwise ### Response Example { "boolean": true } ``` -------------------------------- ### isAutoDeriveColumnNames Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/query.md Gets whether the automatic column name derivation (snake_case to camelCase conversion) is currently enabled for this query. ```APIDOC ## isAutoDeriveColumnNames() ### Description Gets whether automatic column name derivation is enabled. ### Method GET ### Endpoint /query/isAutoDeriveColumnNames ### Response #### Success Response (200) - **boolean** - `true` if enabled, `false` otherwise ### Response Example { "boolean": true } ``` -------------------------------- ### Enable SQL Logging with Logback Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/errors.md Configure Logback to enable DEBUG level logging for the org.sql2o package to view executed SQL statements, parameter values, and execution times. ```xml ``` -------------------------------- ### Use Custom Connection Source Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/advanced.md Instantiate and use a custom ConnectionSource with sql2o. Connections will be automatically routed based on the implemented logic. ```java Map sources = new HashMap<>(); sources.put("primary", primaryDataSource); sources.put("replica", replicaDataSource); ConnectionSource router = new RoutedConnectionSource(sources, "primary"); Sql2o sql2o = new Sql2o(router, quirks); // All connections are routed automatically try (Connection con = sql2o.open()) { List users = con.createQuery("SELECT * FROM users") .executeAndFetch(User.class); } ``` -------------------------------- ### Get Database Quirks Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/quick-reference.md Retrieves the database-specific quirks object used internally by sql2o for handling database variations. ```java Quirks quirks = sql2o.getQuirks(); // Used internally for database-specific handling ``` -------------------------------- ### POJO with Getters and Setters Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/quick-reference.md Demonstrates a POJO using private fields with public getter and setter methods, along with a required public no-arg constructor. ```java // With getters/setters class User { private int id; private String name; public User() {} public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` -------------------------------- ### Get Converter If Exists Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/converters.md Retrieves a converter for a given class. Returns null if no converter is registered for the specified class. ```java public static Converter getConverterIfExists(Class clazz) ``` -------------------------------- ### Check ResultSetIterable Auto-Close Connection Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Gets whether the connection associated with the ResultSetIterable should be automatically closed when iteration completes. ```java boolean isAutoCloseConnection() ``` -------------------------------- ### Configure Default Column Mappings Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/best-practices.md Set global default column mappings and case sensitivity once at startup for all subsequent queries to avoid repetitive configuration. ```java // Set global defaults when creating Sql2o Map mappings = new HashMap<>(); mappings.put("created_at", "createdAt"); mappings.put("updated_at", "updatedAt"); sql2o.setDefaultColumnMappings(mappings); sql2o.setDefaultCaseSensitive(false); // Now all queries use these settings automatically ``` ```java // Configuring every single query is repetitive Query query1 = con.createQuery("SELECT * FROM users") .setColumnMappings(mappings) .setCaseSensitive(false); Query query2 = con.createQuery("SELECT * FROM orders") .setColumnMappings(mappings) .setCaseSensitive(false); ``` -------------------------------- ### Enable Custom Converter with NoQuirks Source: https://github.com/aaberg/sql2o/wiki/Implementing-and-using-custom-converters This Java code demonstrates an alternative method to enable a custom converter by providing a map of converters to the `NoQuirks` constructor during `Sql2o` instantiation. ```java final Map mappers = new HashMap<>(); mappers.put(LocalDate.class, new LocalDateConverter()); final Sql2o database = new Sql2o(embeddedDatabaseRule.getDataSource(), new NoQuirks(mappers)); ``` -------------------------------- ### Get Date by Column Name Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Retrieves a column value as a java.util.Date using its name. The column name is required. ```java public Date getDate(String columnName) ``` -------------------------------- ### Get Date by Column Index Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Retrieves a column value as a java.util.Date using its index. The column index is required. ```java public Date getDate(int columnIndex) ``` -------------------------------- ### Manual Transaction with Custom Connection Source Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/interfaces.md Begin a manual transaction using a custom ConnectionSource. This allows for advanced scenarios where a specific connection provider is required for transaction management. ```java ConnectionSource customSource = /* custom implementation */; // Use custom source for this transaction Connection con = sql2o.beginTransaction(customSource); try { // execute statements con.commit(); } catch (Exception e) { con.rollback(); throw e; } ``` -------------------------------- ### Open Connection with Alternative ConnectionSource Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/sql2o-main.md Opens a new database connection using a provided alternative ConnectionSource implementation. ```java public Connection open(ConnectionSource connectionSource) ``` -------------------------------- ### Get BigDecimal by Column Name Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Retrieves a column value as a BigDecimal using its name. The column name is required. ```java public BigDecimal getBigDecimal(String columnName) ``` -------------------------------- ### Get BigDecimal by Column Index Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Retrieves a column value as a BigDecimal using its index. The column index is required. ```java public BigDecimal getBigDecimal(int columnIndex) ``` -------------------------------- ### Create Sql2o with JNDI Lookup Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/sql2o-main.md Instantiate Sql2o using a JNDI lookup string for the DataSource. Ensure the JNDI name is correctly configured in your application server. ```java public Sql2o(String jndiLookup) ``` ```java Sql2o sql2o = new Sql2o("java:comp/env/jdbc/MyDataSource"); try (Connection con = sql2o.open()) { // use connection } ``` -------------------------------- ### Create Sql2o with DataSource and Quirks Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/sql2o-main.md Create a Sql2o instance with a DataSource and an explicit Quirks object for fine-grained control over database-specific behaviors. ```java public Sql2o(DataSource dataSource, Quirks quirks) ``` -------------------------------- ### Get Byte by Column Name Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Retrieves a column value as a Byte using its name. The column name is required. ```java public Byte getByte(String columnName) ``` -------------------------------- ### Get Byte by Column Index Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Retrieves a column value as a Byte using its index. The column index is required. ```java public Byte getByte(int columnIndex) ``` -------------------------------- ### Create Query with Positional Parameter Binding Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/connection.md This method is for creating a Query where parameters are bound immediately using positional placeholders (`?` or `:p1`, `:p2`). It simplifies queries with multiple parameters. ```java public Query createQueryWithParams(String queryText, Object... paramValues) ``` ```java List users = con.createQueryWithParams( "SELECT * FROM users WHERE name = :p1 AND active = :p2", "John", true ).executeAndFetch(User.class); ``` -------------------------------- ### Get Short by Column Name Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Retrieves a column value as a Short using its name. The column name is required. ```java public Short getShort(String columnName) ``` -------------------------------- ### Get Short by Column Index Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Retrieves a column value as a Short using its index. The column index is required. ```java public Short getShort(int columnIndex) ``` -------------------------------- ### Manual Transaction Management Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/connection.md Illustrates manual transaction control using beginTransaction(), commit(), and rollback(). This pattern is useful for complex operations requiring explicit transaction boundaries. ```java Connection con = sql2o.beginTransaction(); try { con.createQuery("INSERT INTO audit_log (action) VALUES (:action)") .addParameter("action", "USER_LOGIN") .executeUpdate(); con.commit(); } catch (Exception e) { con.rollback(); throw e; } ``` -------------------------------- ### Get Boolean by Column Name Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Retrieves a column value as a Boolean using its name. The column name is required. ```java public Boolean getBoolean(String columnName) ``` -------------------------------- ### Get Boolean by Column Index Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Retrieves a column value as a Boolean using its index. The column index is required. ```java public Boolean getBoolean(int columnIndex) ``` -------------------------------- ### open() Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/sql2o-main.md Opens a new, independent database connection. This connection should be managed (e.g., closed) by the caller, typically using a try-with-resources statement. ```APIDOC ## open() ### Description Opens a new database connection. ### Returns A new `Connection` instance ### Throws - Sql2oException if connection cannot be acquired ### Example ```java try (Connection con = sql2o.open()) { List users = con.createQuery("SELECT * FROM users") .executeAndFetch(User.class); } ``` ``` -------------------------------- ### beginTransaction(ConnectionSource connectionSource, int isolationLevel) Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/sql2o-main.md Begins a transaction using an alternative ConnectionSource with a specified isolation level. Combines the flexibility of an alternative connection source with explicit transaction isolation control. ```APIDOC ## beginTransaction(ConnectionSource connectionSource, int isolationLevel) ### Description Begins a transaction using an alternative ConnectionSource with a specified isolation level. ### Method Not applicable (Java method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **connectionSource** (ConnectionSource) - Required - Alternative connection source implementation - **isolationLevel** (int) - Required - SQL isolation level ### Response #### Success Response - **Connection** - A `Connection` instance in transaction mode ``` -------------------------------- ### Get Float by Column Name Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Retrieves a column value as a Float using its name. The column name is required. ```java public Float getFloat(String columnName) ``` -------------------------------- ### Set Transaction Isolation Level Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/advanced.md Specify the transaction isolation level when starting a new transaction. Defaults to TRANSACTION_READ_COMMITTED. ```java // TRANSACTION_READ_UNCOMMITTED - lowest isolation sql2o.beginTransaction(java.sql.Connection.TRANSACTION_READ_UNCOMMITTED); // TRANSACTION_READ_COMMITTED - default sql2o.beginTransaction(java.sql.Connection.TRANSACTION_READ_COMMITTED); // TRANSACTION_REPEATABLE_READ - intermediate sql2o.beginTransaction(java.sql.Connection.TRANSACTION_REPEATABLE_READ); // TRANSACTION_SERIALIZABLE - highest isolation sql2o.beginTransaction(java.sql.Connection.TRANSACTION_SERIALIZABLE); ``` -------------------------------- ### Configure H2 Database Connection on Android Source: https://github.com/aaberg/sql2o/wiki/Sql2o-on-Android Sets up the database URL and initializes sql2o for an H2 database on Android. Ensure H2 and sql2o JARs are in your project's libs folder. ```java File dbDir = context.getDir("db", 0); dbUrl = "jdbc:h2:file:" + dbDir.getPath() + "/mydb" + ";FILE_LOCK=FS;PAGE_SIZE=1024;CACHE_SIZE=8192"; dbUser = "sa"; sql2o = new Sql2o(dbUrl, dbUser, ""); ``` -------------------------------- ### Get Quirks Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/sql2o-main.md Retrieves the `Quirks` instance associated with this `Sql2o` object. The `Quirks` object handles database-specific behaviors and syntax. ```java public Quirks getQuirks() ``` -------------------------------- ### Get ConnectionSource Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/sql2o-main.md Retrieves the `ConnectionSource` instance currently used by the `Sql2o` object. This source manages the underlying database connections. ```java public ConnectionSource getConnectionSource() ``` -------------------------------- ### Accessing Database Quirks in Java Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/advanced.md Retrieve and inspect database-specific quirks using `getQuirks()`. Check for default behavior like returning generated keys or obtain type converters. ```java Quirks quirks = sql2o.getQuirks(); // Check if this database returns generated keys by default if (quirks.returnGeneratedKeysByDefault()) { // Database-specific behavior } // Get converter for a type Converter uuidConverter = quirks.converterOf(UUID.class); ``` -------------------------------- ### Sql2o(DataSource dataSource, Quirks quirks) Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/sql2o-main.md Creates a new Sql2o instance using a DataSource and explicitly specifying database quirks. ```APIDOC ## Sql2o(DataSource dataSource, Quirks quirks) ### Description Creates a new Sql2o instance using a DataSource with explicit Quirks specification. ### Parameters #### Path Parameters - **dataSource** (DataSource) - Required - JDBC DataSource to use for connections - **quirks** (Quirks) - Required - Database-specific quirks and workarounds ``` -------------------------------- ### Get All Generated Keys Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/connection.md Retrieves all generated keys from the last executeUpdate() call as an array. This method requires that returnGeneratedKeys was enabled for the query. ```java public Object[] getKeys() Gets all generated keys from the last `executeUpdate()` call. **Returns:** Array of generated keys, or `null` if none were generated **Throws:** `Sql2oException` if `returnGeneratedKeys` was not enabled ``` -------------------------------- ### Register Custom Converters with ServiceLoader Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/advanced.md Implement `ConvertersProvider` to register custom converters. Sql2o discovers these providers via the `ServiceLoader` mechanism. ```java import org.sql2o.converters.ConvertersProvider; import java.util.Map; public class CustomConvertersProvider implements ConvertersProvider { @Override public void fill(Map, Converter> converters) { converters.put(PhoneNumber.class, new PhoneNumberConverter()); converters.put(Color.class, new ColorConverter()); converters.put(JSON.class, new JSONConverter()); } } ``` -------------------------------- ### Load SQL2O Credentials from Properties File Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/best-practices.md Securely manage database credentials by loading them from a properties file instead of hardcoding them directly in your application. Ensure the properties file is stored in a secure location. ```properties db.url=jdbc:postgresql://localhost/mydb db.user=appuser db.password=secure_password ``` ```java Properties props = new Properties(); props.load(new FileInputStream("credentials.properties")); Sql2o sql2o = new Sql2o(props.getProperty("db.url"), props.getProperty("db.user"), props.getProperty("db.password")); ``` ```java Sql2o sql2o = new Sql2o("jdbc:postgresql://localhost/mydb", "user", "password123"); ``` -------------------------------- ### Row.getFloat(int columnIndex) Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Gets a column value by index as Float. Retrieve single-precision floating-point numbers by their column index with this method. ```APIDOC ## getFloat(int columnIndex) ### Description Gets a column value by index as Float. Retrieve single-precision floating-point numbers by their column index with this method. ### Method Java Method ### Parameters #### Path Parameters - **columnIndex** (int) - Required - Column index ### Returns #### Success Response - **Float** - Float value or null ``` -------------------------------- ### open(ConnectionSource connectionSource) Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/sql2o-main.md Opens a new database connection using an alternative ConnectionSource implementation. This allows for custom connection management strategies. ```APIDOC ## open(ConnectionSource connectionSource) ### Description Opens a new database connection using an alternative ConnectionSource. ### Parameters #### Path Parameters - **connectionSource** (ConnectionSource) - Required - Alternative connection source implementation ### Returns A new `Connection` instance ``` -------------------------------- ### Row.getLong(String columnName) Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Gets a column value by name as Long. This method facilitates retrieving long data by its column name. ```APIDOC ## getLong(String columnName) ### Description Gets a column value by name as Long. This method facilitates retrieving long data by its column name. ### Method Java Method ### Parameters #### Path Parameters - **columnName** (String) - Required - Column name ### Returns #### Success Response - **Long** - Long value or null ``` -------------------------------- ### POJO with Custom Mapping and Constructor Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/quick-reference.md Illustrates a POJO requiring a public no-argument constructor for instantiation, alongside public fields for mapping. ```java // With custom mapping class User { public int id; public String name; public String email; public User() {} // Required: public no-arg constructor } ``` -------------------------------- ### Fetch All Tasks as Model Objects Source: https://github.com/aaberg/sql2o/wiki/Documentation/Fetching-data-from-database Retrieve all records from the 'tasks' table and map them to a list of Task objects. Ensure the sql2o instance is properly configured. ```java public List getAllTasks(){ String sql = "SELECT id, description, duedate " + "FROM tasks"; try(Connection con = sql2o.open()) { return con.createQuery(sql).executeAndFetch(Task.class); } } ``` -------------------------------- ### Get First Generated Key Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/connection.md Retrieves the first generated key from the last executeUpdate() call. This method requires that returnGeneratedKeys was enabled for the query. ```java public Object getKey() Gets the first generated key from the last `executeUpdate()` call. **Returns:** The generated key, or `null` if none was generated **Throws:** `Sql2oException` if `returnGeneratedKeys` was not enabled ``` ```java con.createQuery("INSERT INTO users (name) VALUES (:name)", true) .addParameter("name", "John") .executeUpdate(); long userId = ((Number) con.getKey()).longValue(); ``` -------------------------------- ### Include a Public No-Arg Constructor Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/best-practices.md SQL2O requires a public no-argument constructor to instantiate POJOs before mapping data. Ensure your class has one, even if other constructors are present. ```java class User { public int id; public String name; public User() {} // Required for mapping } ``` ```java class User { public int id; public String name; public User(String name) { // Only non-default constructor this.name = name; } } ``` -------------------------------- ### Row.getDouble(String columnName) Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Gets a column value by name as Double. This method allows for retrieving double values using the column name. ```APIDOC ## getDouble(String columnName) ### Description Gets a column value by name as Double. This method allows for retrieving double values using the column name. ### Method Java Method ### Parameters #### Path Parameters - **columnName** (String) - Required - Column name ### Returns #### Success Response - **Double** - Double value or null ``` -------------------------------- ### Row.getDouble(int columnIndex) Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Gets a column value by index as Double. Use this method to access double-precision floating-point numbers by their column index. ```APIDOC ## getDouble(int columnIndex) ### Description Gets a column value by index as Double. Use this method to access double-precision floating-point numbers by their column index. ### Method Java Method ### Parameters #### Path Parameters - **columnIndex** (int) - Required - Column index ### Returns #### Success Response - **Double** - Double value or null ``` -------------------------------- ### Row.getLong(int columnIndex) Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/data-structures.md Gets a column value by index as Long. Retrieve long values from a specific column index using this method. ```APIDOC ## getLong(int columnIndex) ### Description Gets a column value by index as Long. Retrieve long values from a specific column index using this method. ### Method Java Method ### Parameters #### Path Parameters - **columnIndex** (int) - Required - Column index ### Returns #### Success Response - **Long** - Long value or null ``` -------------------------------- ### executeAndFetchTable Source: https://github.com/aaberg/sql2o/blob/master/_autodocs/query.md Executes the query and returns all results as a Table object, which provides a generic row and column structure. ```APIDOC ## executeAndFetchTable() ### Description Executes the query and returns results as a Table (generic row/column structure). ### Method `executeAndFetchTable` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Returns A `Table` object containing all rows and column metadata ### Example ```java Table table = con.createQuery("SELECT * FROM users") .executeAndFetchTable(); for (Row row : table.rows()) { String name = row.getString("name"); } ``` ```