2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

RustでPostgreSQLに接続する

Posted at

概要

RustからPostgreSQLに接続し、select文を実行するところをまでを
試してみた作業メモです。

今回、接続にこちらのクレートを使います。
https://docs.rs/postgres/

プロジェクトの作成

% cargo new connect_postgres
% cd connect_postgres

src/main.rspostgres の extern を追加

extern crate postgres;

fn main() {
    println!("Hello, world!");
}

一度 cargo run する

postgres クレートに必要なライブラリのダウンロード、コンパイルが行われ、
その後に実行される。

% cargo run
    Updating crates.io index
  Downloaded block-buffer v0.10.2
  Downloaded futures-task v0.3.21
  ...
   Compiling futures v0.3.21
   Compiling tokio-postgres v0.7.6
   Compiling postgres v0.19.3
   Compiling connect_postgres v0.1.0 (/Users/username/src/github.com/username/rust-study/connect_postgres)
    Finished dev [unoptimized + debuginfo] target(s) in 1m 46s
     Running `target/debug/connect_postgres`
Hello, world!

PostgreSQLに検証用データを作成する。

下記のdocker-compose.ymlでdocker-commpose upする。

version: "3.9"

services:
  postgres:
    image: postgres:14.3-alpine3.16
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: password
    ports:
      - 5432:5432
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:

検証用データのinsert。

# create database testdb;
# \c testdb
# create table users (id int, name varchar);
# insert into users values (1, 'name1'), (2, 'name2');

Rustから接続する

postgres crateの例を参考にselectするプログラムを記述。
https://docs.rs/postgres/latest/postgres/#example

extern crate postgres;
use postgres::{Client, Error, NoTls};

fn main() -> Result<(), Error> {
    let mut client = Client::connect(
        "postgresql://postgres:password@127.0.0.1:5432/testdb",
        NoTls,
    )?;

    for row in client.query("SELECT id, name FROM users", &[])? {
        let id: i32 = row.get(0);
        let name: String = row.get(1);
        println!("{} {}", id, name);
    }

    Ok(())
}

実行

% cargo run
   Compiling connect_postgres v0.1.0 (/Users/username/src/github.com/username/rust-study/connect_postgres)
    Finished dev [unoptimized + debuginfo] target(s) in 0.98s
     Running `target/debug/connect_postgres`
1 name1
2 name2
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?