我在后端使用 Go。我尝试编写一个函数,该函数采用数据库名称并使用该名称创建 PostgreSQL 数据库。在这个函数之后应该在这个数据库中创建表(我已经为这个任务创建了一个 sql 脚本)
所以主要问题是我不明白如何编写一个函数来创建 PostgreSQL 数据库。我想创建一个 .sql 文件并以某种方式将数据库名称传递给该文件(例如在 .sql 文件中查找字符串,它看起来像 {{dbname}} 并将其替换为数据库名称),但可能有一个更好的方法?
这是我的 .sql 文件,它应该在新的 PostgreSQL 数据库中创建表
create table "reviews"
(
review_id uuid not null
constraint review_pk
primary key,
user_id uuid not null,
rating float,
comment text,
date date not null
);
create unique index reviews_review_id_uindex
on "reviews" (review_id);
create unique index reviews_user_id_uindex
on "reviews" (user_id);
create table "sections"
(
section_id uuid not null
constraint section_pk
primary key,
title text not null,
color text,
created_at date not null,
updated_at date not null,
deleted boolean default false
);
create unique index sections_section_id_uindex
on "sections" (section_id);
最佳答案
试试这个,
package main
import (
"database/sql"
"log"
_ "github.com/lib/pq"
)
func main() {
conninfo := "user=postgres password=yourpassword
host=127.0.0.1 sslmode=disable"
db, err := sql.Open("postgres", conninfo)
if err != nil {
log.Fatal(err)
}
dbName := "testdb"
_, err = db.Exec("create database " + dbName)
if err != nil {
//handle the error
log.Fatal(err)
}
//Then execute your query for creating table
_, err = db.Exec("CREATE TABLE example ( id integer,
username varchar(255) )")
if err != nil {
log.Fatal(err)
}
}
注意:postgress 中所有的查询语句都不支持参数,比如 ("create database $1", "testdb")
将不起作用。
关于sql - 是否可以在 Golang 的帮助下创建具有动态名称的 PostgreSQL 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55555836/