# Kotlin

Connect to ParticleDB from Kotlin, run parameterized queries, handle transactions and errors.

Source: https://particledb.ai/sdks/kotlin/

Use the configured address for your client. See [connection addresses](/installation/ports/) and [security](/guides/security/). The examples use the SQL client address unless they explicitly select the HTTP API or ParticleDB JDBC driver.

Kotlin on the JVM connects to ParticleDB through JDBC, with either the standard PostgreSQL
JDBC driver (SQL client interface, port 5432) or the ParticleDB JDBC driver
`ai.particledb:particledb-jdbc` (ParticleDB JDBC interface, port 7173). Both are described on
[Java and JDBC](/sdks/java/).

## Install

```kotlin
// build.gradle.kts
dependencies {
    implementation("org.postgresql:postgresql:42.7.11")
    // or the ParticleDB JDBC driver:
    // implementation("ai.particledb:particledb-jdbc:1.0.12")
}
```

## Quick start

The example connects as `postgres` with the password `secret`, for a server started with
`particledb start --auth-method scram-sha-256 --pg-password secret`.

```kotlin
import java.sql.DriverManager

fun main() {
    DriverManager.getConnection(
        "jdbc:postgresql://localhost:5432/particledb", "postgres", "secret"
    ).use { conn ->
        conn.createStatement().use {
            it.execute("CREATE TABLE users (id BIGINT PRIMARY KEY, name TEXT)")
        }

        conn.prepareStatement("INSERT INTO users (id, name) VALUES (?, ?)").use { ps ->
            ps.setLong(1, 1)
            ps.setString(2, "Alice")
            ps.executeUpdate()
        }

        conn.prepareStatement("SELECT id, name FROM users WHERE id = ?").use { ps ->
            ps.setLong(1, 1)
            ps.executeQuery().use { rs ->
                while (rs.next()) println("${rs.getLong("id")} ${rs.getString("name")}")
            }
        }
    }
}
```

Output:

```
1 Alice
```

To use the ParticleDB JDBC driver instead, change the URL to
`jdbc:particledb://localhost:7173/particledb`. No JVM flags are needed.
For an encrypted connection, see [TLS](/sdks/java/#tls).

## Android

JDBC drivers are not a good fit for Android apps, and an app installed on users' devices
should not hold database credentials. Call your own backend service from the app, and let that
service talk to ParticleDB.

## Next steps

- [Java and JDBC](/sdks/java/). both drivers in depth
- [SQL Reference](/sql/overview/). SQL syntax and examples
