# 使用 Dart 連線至 Turso

> 使用 Dart 連線至 Turso — Turso 官方文件。
> Canonical HTML: https://tursodb.cn/zh-tw/docs/connect/dart/
> Upstream Source (MIT): https://docs.turso.tech/connect/dart
> Language: zh-TW

---
**1. 安裝**

將 `turso_dart` 套件加入您的 `pubspec.yaml`：

```yaml
dependencies:
  turso_dart:
```

接著執行：

```bash
dart pub get
```

**2. 連線**

建立用戶端連線。您可以連線至記憶體內資料庫或本機檔案：

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

// In memory
final client = TursoClient.memory();

// Or local file
final client = TursoClient.local('/path/to/local.db');

await client.connect();
```

**3. 建立資料表**

建立一個用於儲存客戶的資料表：

```dart
await client.execute(
  "CREATE TABLE IF NOT EXISTS customers (id INTEGER PRIMARY KEY, name TEXT)"
);
```

**4. 寫入資料**

在 `customers` 資料表中新增幾筆資料：

```dart
await client.query("INSERT INTO customers(name) VALUES ('John Doe')");
await client.query("INSERT INTO customers(name) VALUES ('Jane Smith')");
```

**5. 查詢資料**

從資料表中查詢所有客戶：

```dart
final result = await client.query("SELECT * FROM customers");
print(result);
```

**6. 預備陳述式**

使用預備陳述式以獲得更佳的效能與安全性：

```dart
final statement = await client.prepare("SELECT * FROM customers WHERE id = ?");
final result = await statement.query(positional: [1]);
print(result);
```
