sql - 是否可以在 Golang 的帮助下创建具有动态名称的 PostgreSQL 数据库?

标签 sql database postgresql go

我在后端使用 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/

相关文章:

php - 如果未找到 array_search 查询

database - 无法将数据添加到 Firestore 数据库

postgresql - 有没有办法在 windows cli 中使用 'COPY' 命令(PostgreSQL)?

postgresql - 如何使用 KnexJS 创建值列表

sql - 来自 DateTimePicker 的 SQL 字符串中的日期

sql - OLE DB 提供程序 'Microsoft.Jet.OLEDB.4.0' 无法用于分布式查询

php - 简单的数据库设计问题

java - 如何使用 Spring Data JPA 查询更新 PostgreSQL 中的 JSONB 列

sql - 使用 postgres 从最后一个插入查询获取数据

PHP 在另一个 SQL 语句中运行 SQL 结果