Skip to content

Latest commit

 

History

History
36 lines (25 loc) · 1.29 KB

create_tables.zh.md

File metadata and controls

36 lines (25 loc) · 1.29 KB

在 Postgres 数据库中,创建表

[![postgres-badge]][postgres] [![cat-database-badge]][cat-database]

使用postgres在 Postgres 数据库中,创建表。

Connection::connect帮助连接到现有数据库。该食谱的Connection::connect使用一个 URL 字符串格式。 它假定一个名为library,用户名是postgres,密码是postgres.

extern crate postgres;

use postgres::{Connection, TlsMode, Error};

fn main() -> Result<(), Error> {
    let conn = Connection::connect("postgresql://postgres:postgres@localhost/library",
                                    TlsMode::None)?;

     conn.execute("CREATE TABLE IF NOT EXISTS author (
                    id              SERIAL PRIMARY KEY,
                    name            VARCHAR NOT NULL,
                    country         VARCHAR NOT NULL
                  )", &[])?;

    conn.execute("CREATE TABLE IF NOT EXISTS book  (
                    id              SERIAL PRIMARY KEY,
                    title           VARCHAR NOT NULL,
                    author_id       INTEGER NOT NULL REFERENCES author
                )", &[])?;

    Ok(())

}