# Dart

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

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

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.

Use [`package:postgres`](https://pub.dev/packages/postgres) (version 3) over the SQL client interface
(port 5432) from server-side or command-line Dart.

## Install

```yaml
# pubspec.yaml
dependencies:
  postgres: ^3.4.0
```

## 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`. With the server's default
`--auth-method password`, use `SslMode.require`; see
[TLS and authentication](/connectivity/tls/#authentication).

```dart
import 'package:postgres/postgres.dart';

Future<void> main() async {
  final conn = await Connection.open(
    Endpoint(
      host: 'localhost',
      port: 5432,
      database: 'particledb',
      username: 'postgres',
      password: 'secret',
    ),
    settings: ConnectionSettings(sslMode: SslMode.disable),
  );

  await conn.execute('CREATE TABLE users (id BIGINT PRIMARY KEY, name TEXT)');

  final ins = await conn.execute(
    Sql.named('INSERT INTO users (id, name) VALUES (@id, @name)'),
    parameters: {'id': 1, 'name': 'Alice'},
  );
  print(ins.affectedRows); // 1

  final rows = await conn.execute(
    Sql.named('SELECT id, name FROM users WHERE id = @id'),
    parameters: {'id': 1},
  );
  for (final row in rows) {
    print(row.toColumnMap()); // {id: 1, name: Alice}
  }

  // Transaction: commits when the callback returns, rolls back if it throws
  await conn.runTx((tx) async {
    await tx.execute(
      Sql.named('INSERT INTO users (id, name) VALUES (@id, @name)'),
      parameters: {'id': 2, 'name': 'Bob'},
    );
  });

  final count = await conn.execute('SELECT count(*) FROM users');
  print(count.first.first); // 2

  await conn.close();
}
```

Output:

```
1
{id: 1, name: Alice}
2
```

## Flutter apps

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

- [SQL Reference](/sql/overview/). SQL syntax and examples
- [SQL client connections](/connectivity/pg-wire/). connection settings and compatibility
- [Vector Search](/sql/vector-search/). vector search SQL syntax
