サンプル集  >  other  >  MySQLへ接続 (mysqlクレート(同期版))
MySQLへ接続 (mysqlクレート(同期版))
2025/09/13

mysqlクレートを使ってMySQLへ接続してみます。

◆環境
OS Windows 10 Home 22H2 64bit
rustc 1.86.0
cargo 1.86.0

Cargo.tomlファイルに依存関係を追記します。

Cargo.toml
1: 
2: 
3: 
4: 
5: 
6: 
7: 
[package]
name = "ymwrust010"
version = "0.1.0"
edition = "2024"

[dependencies]
mysql = "26.0.1"

MySQLへ接続しバージョン番号を表示するようにしてみます。

main.rs
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
use mysql::{Opts, Conn};

fn main() {
    println!("Hello, world!");
    let url="mysql://root:root@localhost:3306/MyDB";
    let opts = Opts::from_url(url).unwrap();

    let conn = Conn::new(opts).unwrap();

    let version = conn.server_version();
    println!("version={}.{}.{}"
            , version.0
            , version.1
            , version.2
            );
}

cargo runで実行したところ正常にMySQLへ接続しバージョン番号を取得できたようです。

cargo run
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.1
9s
     Running `target\debug\ymwrust010.exe`
Hello, world!
version=8.0.41

MySQLへ接続できない場合、以下のエラーがでました。

cargo run
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.2
0s
     Running `target\debug\ymwrust010.exe`
Hello, world!

thread 'main' panicked at src\main.rs:8:32:
called `Result::unwrap()` on an `Err` value: DriverError { Could not 
connect to address `localhost:3306': 対象のコンピューターによって拒
否されたため、接続できませんでした。 (os error 10061) }
note: run with `RUST_BACKTRACE=1` environment variable to display a b
acktrace
error: process didn't exit successfully: `target\debug\ymwrust010.exe
` (exit code: 101)

期待通りに動きました。

▲ PageTop  ■ Home


Copyright (C) 2025 ymlib.com