| Linuxコマンド |
| 用語集 |
| debian メモ |
| apache2 メモ |
| MySQL メモ |
| Oracle メモ |
| PostgreSQL |
| HOME |
RustでSQLxクレートを使ってMySQLのデータを検索してみます。
◆環境| OS | Windows 11 Home 25H2 |
|---|---|
| rustc | 1.91.1 |
| cargo | 1.91.1 |
プロジェクトの作成
プロジェクトを作成します。
cargo new sqlxtest
コマンドプロンプトでプロジェクトを作成したいフォルダへ移動しコマンドを実行します。
> cargo new sqlxtest
Creating binary (application) `sqlxtest` package
warning: compiling this new package may not work due to invalid works
pace configuration
failed to parse manifest at `C:\src\Cargo.toml`
Caused by:
no targets specified in the manifest
either src/lib.rs, src/main.rs, a [lib] section, or [[bin]] section
must be present
note: see more `Cargo.toml` keys and their definitions at https://doc
.rust-lang.org/cargo/reference/manifest.html
Creating binary (application) `sqlxtest` package
warning: compiling this new package may not work due to invalid works
pace configurationfailed to parse manifest at `C:\src\Cargo.toml`
Caused by:
no targets specified in the manifest
either src/lib.rs, src/main.rs, a [lib] section, or [[bin]] section
must be presentnote: see more `Cargo.toml` keys and their definitions at https://doc
.rust-lang.org/cargo/reference/manifest.htmlプログラム作成
ポイントは以下になります。
- コネクションプールを使う。(MySqlPoolOptions::new())
- プリペアドステートメントを使う。(?とbind())
- 接続文字列はハードコーディングせず.envで管理する。
| Cargo.toml | ||
|
| main.rs | ||
|
DBはDocker上に構築していてlocalhost:13306で待ち受けているのでポートは13306にしました。
docker container restart mysql-container-8.0.41
| .env | ||
|
テーブルとテストデータを作成します。
| sql-rec_values.txt | ||
|
実行してみます。
PS C:\src\sqlxtest> cargo run
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.2
5s
Running `target\debug\sqlxtest.exe`
Hello, world!
mysql://root:root@localhost:13306/MyDB
id=1 date=2026-03-15 09:22:16 value=12.3
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.2
5sRunning `target\debug\sqlxtest.exe`
Hello, world!
mysql://root:root@localhost:13306/MyDB
id=1 date=2026-03-15 09:22:16 value=12.3
MySQLで接続数を確認したところ実行中は1増えていました。
mysql> SHOW STATUS LIKE 'Threads_connected';
+-------------------+-------+
| Variable_name | Value |
+-------------------+-------+
| Threads_connected | 2 |
+-------------------+-------+
1 row in set (0.00 sec)
+-------------------+-------+
| Variable_name | Value |
+-------------------+-------+
| Threads_connected | 2 |
+-------------------+-------+
1 row in set (0.00 sec)
期待通りに動作しました。
関連項目
Docker MySQL
MySQLでテーブル作成、データ追加、検索
MySQLのデータ検索(SQLx)②
MySQLのデータ追加(SQLx)
Copyright (C) 2026 ymlib.com
