api-docs / org.ktorm.database / Database
Database
class Database
(source code)The entry class of Ktorm, represents a physical database, used to manage connections and transactions.
Connect with a URL
The simplest way to create a database instance, using a JDBC URL:
val database = Database.connect("jdbc:mysql://localhost:3306/ktorm", user = "root", password = "123")
Easy to know what we do in the connect function. Just like any JDBC boilerplate code, Ktorm loads the MySQL
database driver first, then calls DriverManager.getConnection with your URL to obtain a connection.
Of course, Ktorm doesn’t call DriverManager.getConnection in the beginning. Instead, we obtain connections
only when it’s really needed (such as executing a SQL), then close them after they are not useful anymore.
Therefore, database objects created by this way won’t reuse any connections, creating connections frequently
can lead to huge performance costs. It’s highly recommended to use connection pools in your production environment.
Connect with a Pool
Ktorm doesn’t limit you, you can use any connection pool you like, such as DBCP, C3P0 or Druid. The connect
function provides an overloaded version which accepts a DataSource parameter, you just need to create a
DataSource object and call that function with it:
val dataSource = SingleConnectionDataSource() // Any DataSource implementation is OK.
val database = Database.connect(dataSource)
Now, Ktorm will obtain connections from the DataSource when necessary, then return them to the pool after they
are not useful. This avoids the performance costs of frequent connection creation.
Connection pools are applicative and effective in most cases, we highly recommend you manage your connections
in this way.
Use SQL DSL & Sequence APIs
Now that we’ve connected to the database, we can perform many operations on it. Ktorm’s APIs are mainly divided
into two parts, they are SQL DSL and sequence APIs.
Here, we use SQL DSL to obtains the names of all engineers in department 1:
database
.from(Employees)
.select(Employees.name)
.where { (Employees.departmentId eq 1) and (Employees.job eq "engineer") }
.forEach { row ->
println(row[Employees.name])
}
Equivalent code using sequence APIs:
database
.sequenceOf(Employees)
.filter { it.departmentId eq 1 }
.filter { it.job eq "engineer" }
.mapColumns { it.name }
.forEach { name ->
println(name)
}
More details about SQL DSL, see Query, about sequence APIs, see EntitySequence.
Constructors
Name | Summary |
---|---|
Database( The entry class of Ktorm, represents a physical database, used to manage connections and transactions. |
Properties
Name | Summary |
---|---|
val alwaysQuoteIdentifiers: Boolean Whether we need to always quote SQL identifiers in the generated SQLs. | |
val dialect: SqlDialect The dialect, auto-detects an implementation by default using JDK ServiceLoader facility. | |
val exceptionTranslator: ((SQLException) -> Throwable)? Function used to translate SQL exceptions to rethrow them to users. | |
val extraNameCharacters: String All the “extra” characters that can be used in unquoted identifier names (those beyond a-z, A-Z, 0-9 and _). | |
val generateSqlInUpperCase: Boolean? Whether we need to output the generated SQLs in upper case. | |
val identifierQuoteString: String The string used to quote SQL identifiers, returns an empty string if identifier quoting is not supported. | |
A set of all of this database’s SQL keywords (including SQL:2003 keywords), all in uppercase. | |
val logger: Logger The logger used to output logs, auto-detects an implementation by default. | |
val maxColumnNameLength: Int The maximum number of characters this database allows for a column name. Zero means that there is no limit | |
val name: String The name of the connected database. | |
val productName: String The name of the connected database product, eg. MySQL, H2. | |
val productVersion: String The version of the connected database product. | |
val storesLowerCaseIdentifiers: Boolean Whether this database treats mixed case unquoted SQL identifiers as case-insensitive and | |
val storesLowerCaseQuotedIdentifiers: Boolean Whether this database treats mixed case quoted SQL identifiers as case-insensitive and | |
val storesMixedCaseIdentifiers: Boolean Whether this database treats mixed case unquoted SQL identifiers as case-insensitive and | |
val storesMixedCaseQuotedIdentifiers: Boolean Whether this database treats mixed case quoted SQL identifiers as case-insensitive and | |
val storesUpperCaseIdentifiers: Boolean Whether this database treats mixed case unquoted SQL identifiers as case-insensitive and | |
val storesUpperCaseQuotedIdentifiers: Boolean Whether this database treats mixed case quoted SQL identifiers as case-insensitive and | |
val supportsMixedCaseIdentifiers: Boolean Whether this database treats mixed case unquoted SQL identifiers as case-sensitive and as a result | |
val supportsMixedCaseQuotedIdentifiers: Boolean Whether this database treats mixed case quoted SQL identifiers as case-sensitive and as a result | |
val transactionManager: TransactionManager The transaction manager used to manage connections and transactions. | |
val url: String The URL of the connected database. |
Functions
Name | Summary |
---|---|
fun executeBatch(expressions: List<SqlExpression>): IntArray Batch execute the given SQL expressions and return the effected row counts for each expression. | |
fun <T> executeExpression( Format the given expression to a SQL string with its execution arguments, then create | |
fun executeQuery(expression: SqlExpression): CachedRowSet Format the given expression to a SQL string with its execution arguments, then execute it via | |
fun executeUpdate(expression: SqlExpression): Int Format the given expression to a SQL string with its execution arguments, then execute it via | |
fun executeUpdateAndRetrieveKeys( Format the given expression to a SQL string with its execution arguments, execute it via | |
fun formatExpression( Format the specific SqlExpression to an executable SQL string with execution arguments. | |
fun <T> useConnection(func: (Connection) -> T): T Obtain a connection and invoke the callback function with it. | |
fun <T> useTransaction( Execute the specific callback function in a transaction and returns its result if the execution succeeds, |
Companion Object Functions
Name | Summary |
---|---|
fun connect( Connect to a database by a specific connector function. fun connect( Connect to a database using a DataSource. fun connect( Connect to a database using the specific connection arguments. | |
fun connectWithSpringSupport( Connect to a database using a DataSource with the Spring support enabled. |
Extension Functions
Name | Summary |
---|---|
fun <T : BaseTable<*>> Database.batchInsert( Construct insert expressions in the given closure, then batch execute them and return the effected | |
fun <T : BaseTable<*>> Database.batchUpdate( Construct update expressions in the given closure, then batch execute them and return the effected | |
fun <T : BaseTable<*>> Database.bulkInsert( Construct a bulk insert expression in the given closure, then execute it and return the effected row count. | |
fun <T : BaseTable<*>> Database.bulkInsert( Bulk insert records to the table and return the effected row count. | |
fun <T : BaseTable<*>> Database.bulkInsert( Bulk insert records to the table and return the effected row count. | |
fun <T : BaseTable<*>> Database.bulkInsertOrUpdate( Bulk insert records to the table, determining if there is a key conflict while inserting each of them, | |
fun <T : BaseTable<*>> Database.bulkInsertOrUpdate( Bulk insert records to the table, determining if there is a key conflict while inserting each of them, | |
fun <T : BaseTable<*>> Database.bulkInsertOrUpdate( Bulk insert records to the table, determining if there is a key conflict while inserting each of them, | |
fun <T : BaseTable<*>, C : Any> Database.bulkInsertOrUpdateReturning( Bulk insert records to the table, determining if there is a key conflict while inserting each of them, fun <T : BaseTable<*>, C1 : Any, C2 : Any> Database.bulkInsertOrUpdateReturning( fun <T : BaseTable<*>, C1 : Any, C2 : Any, C3 : Any> Database.bulkInsertOrUpdateReturning( Bulk insert records to the table, determining if there is a key conflict while inserting each of them, | |
fun <T : BaseTable<*>, C : Any> Database.bulkInsertOrUpdateReturning( Bulk insert records to the table, determining if there is a key conflict while inserting each of them, fun <T : BaseTable<*>, C1 : Any, C2 : Any> Database.bulkInsertOrUpdateReturning( fun <T : BaseTable<*>, C1 : Any, C2 : Any, C3 : Any> Database.bulkInsertOrUpdateReturning( Bulk insert records to the table, determining if there is a key conflict while inserting each of them, | |
fun <T : BaseTable<*>, C : Any> Database.bulkInsertReturning( Bulk insert records to the table and return the specific column’s values. fun <T : BaseTable<*>, C1 : Any, C2 : Any> Database.bulkInsertReturning( fun <T : BaseTable<*>, C1 : Any, C2 : Any, C3 : Any> Database.bulkInsertReturning( Bulk insert records to the table and return the specific columns’ values. | |
fun <T : BaseTable<*>, C : Any> Database.bulkInsertReturning( Bulk insert records to the table and return the specific column’s values. fun <T : BaseTable<*>, C1 : Any, C2 : Any> Database.bulkInsertReturning( fun <T : BaseTable<*>, C1 : Any, C2 : Any, C3 : Any> Database.bulkInsertReturning( Bulk insert records to the table and return the specific columns’ values. | |
Delete the records in the table that matches the given predicate. | |
Delete all the records in the table. | |
infix fun <T : Any> T.eq( Equal operator, translated to | |
fun Database.from(table: BaseTable<*>): QuerySource Wrap the specific table as a QuerySource. | |
Construct an insert expression in the given closure, then execute it and return the effected row count. | |
fun <T : BaseTable<*>> Database.insertAndGenerateKey( Construct an insert expression in the given closure, then execute it and return the auto-generated key. | |
fun <T : BaseTable<*>> Database.insertOrUpdate( Insert a record to the table, determining if there is a key conflict while it’s being inserted, and automatically | |
fun <T : BaseTable<*>> Database.insertOrUpdate( Insert a record to the table, determining if there is a key conflict while it’s being inserted, and automatically | |
fun <T : BaseTable<*>> Database.insertOrUpdate( Insert a record to the table, determining if there is a key conflict while it’s being inserted, and automatically | |
fun <T : BaseTable<*>, C : Any> Database.insertOrUpdateReturning( Insert a record to the table, determining if there is a key conflict while it’s being inserted, automatically fun <T : BaseTable<*>, C1 : Any, C2 : Any> Database.insertOrUpdateReturning( fun <T : BaseTable<*>, C1 : Any, C2 : Any, C3 : Any> Database.insertOrUpdateReturning( Insert a record to the table, determining if there is a key conflict while it’s being inserted, automatically | |
fun <T : BaseTable<*>, C : Any> Database.insertOrUpdateReturning( Insert a record to the table, determining if there is a key conflict while it’s being inserted, automatically fun <T : BaseTable<*>, C1 : Any, C2 : Any> Database.insertOrUpdateReturning( fun <T : BaseTable<*>, C1 : Any, C2 : Any, C3 : Any> Database.insertOrUpdateReturning( Insert a record to the table, determining if there is a key conflict while it’s being inserted, automatically | |
fun <T : BaseTable<*>, C : Any> Database.insertReturning( Insert a record to the table and return the specific column. fun <T : BaseTable<*>, C1 : Any, C2 : Any> Database.insertReturning( fun <T : BaseTable<*>, C1 : Any, C2 : Any, C3 : Any> Database.insertReturning( Insert a record to the table and return the specific columns. | |
fun <T : BaseTable<*>, C : Any> Database.insertReturning( Insert a record to the table and return the specific column. fun <T : BaseTable<*>, C1 : Any, C2 : Any> Database.insertReturning( fun <T : BaseTable<*>, C1 : Any, C2 : Any, C3 : Any> Database.insertReturning( Insert a record to the table and return the specific columns. | |
Execute the callback function using the current database instance. | |
infix fun <T : Any> T.neq( Not-equal operator, translated to | |
infix fun <T : Any> T.notEq( Not-equal operator, translated to | |
fun <E : Any, T : BaseTable<E>> Database.sequenceOf( Create an EntitySequence from the specific table. | |
Construct an update expression in the given closure, then execute it and return the effected row count. |
Companion Object Extension Properties
Name | Summary |
---|---|
val Database.Companion. The global database instance, Ktorm uses this property to obtain a database when any SQL is executed. |
Companion Object Extension Functions
Name | Summary |
---|---|
fun Database.Companion. Connect to a database by a specific connector function and save the returned database instance fun Database.Companion. Connect to a database using a DataSource and save the returned database instance to Database.Companion.global. fun Database.Companion. Connect to a database using the specific connection arguments and save the returned database instance | |
fun Database.Companion. Connect to a database using a DataSource with the Spring support enabled and save the returned database |