登录
首页 >  Golang >  Go问答

使用 Golang 创建动态名称的 PostgreSQL 数据库是否可行?

来源:stackoverflow

时间:2024-02-28 09:36:23 425浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《使用 Golang 创建动态名称的 PostgreSQL 数据库是否可行?》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我在后端使用 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") 不起作用。

本篇关于《使用 Golang 创建动态名称的 PostgreSQL 数据库是否可行?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>