English | 简体中文

api-docs / org.ktorm.database / Database / <init>

<init>

Database(
    transactionManager: TransactionManager,
    dialect: SqlDialect = detectDialectImplementation(),
    logger: Logger = detectLoggerImplementation(),
    exceptionTranslator: ((SQLException) -> Throwable)? = null,
    alwaysQuoteIdentifiers: Boolean = false,
    generateSqlInUpperCase: Boolean? = null)

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.