# 使用 Dart 连接 Turso

> 在 Dart 项目中安装并连接 Turso 数据库的快速指南。
> Canonical HTML: https://tursodb.cn/zh-cn/docs/connect/dart/
> Upstream Source (MIT): https://docs.turso.tech/connect/dart
> Language: zh-CN

---
**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. 创建数据表**

创建一张 `customers` 表：

```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. 预处理语句**

使用预处理语句（Prepared Statements）可以获得更好的性能与安全性：

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