11.1.2.1. Postgres 数据库中创建表
Postgres 数据库中,使用 postgres
crate 创建表。
Client::connect
用于连接到现有数据库。本实例中使用 Client::connect
格式化连接数据库的 URL 字符串。假设存在一个数据库:名为 library
,用户名为 postgres
,密码为 postgres
。
use postgres::{Client, NoTls, Error}; fn main() -> Result<(), Error> { let mut client = Client::connect("postgresql://postgres:postgres@localhost/library", NoTls)?; client.batch_execute(" CREATE TABLE IF NOT EXISTS author ( id SERIAL PRIMARY KEY, name VARCHAR NOT NULL, country VARCHAR NOT NULL ) ")?; client.batch_execute(" CREATE TABLE IF NOT EXISTS book ( id SERIAL PRIMARY KEY, title VARCHAR NOT NULL, author_id INTEGER NOT NULL REFERENCES author ) ")?; Ok(()) }