如何使用用户名和密码打开数据库连接

huangapple go评论109阅读模式
英文:

How to open db connection with user and password

问题

在Golang的sql.Open命令中如何包含PostgreSQL的用户名和密码?下面的代码似乎无法正常工作。谢谢!

func db() (database *sql.DB) {
    database, err := sql.Open("postgres", "dbname=chitchat user=tom password=tomtom sslmode=disable")
    if err != nil {
        log.Fatal(err)
    }
    return
}

你可以在连接字符串中直接包含用户名和密码。在上面的代码中,用户名是"tom",密码是"tomtom"。你可以根据你的实际情况修改这些值。

英文:

How do I include postgresql username and password in the sql.Open command in golang? The below doesn't seem to work. Thanks!

func db() (database *sql.DB) {
    database, err := sql.Open("postgres", "dbname=chitchat user=tom password=tomtom sslmode=disable")
	if err != nil {
		log.Fatal(err)
	}
	return
}

答案1

得分: 11

你可以在lib/pq/doc.gomurz/dat(使用lib/pq)中看到示例:

db, err := sql.Open("postgres", "user=pqgotest dbname=pqgotest sslmode=verify-full")
db, err := sql.Open("postgres", "dbname=dat_test user=dat password=!test host=localhost sslmode=disable")

你也可以使用URL连接到数据库。例如:

db, err := sql.Open("postgres", "postgres://pqgotest:password@localhost/pqgotest?sslmode=verify-full")

OP提议:

  1. 授予对数据库的访问权限
    GRANT all privileges on database chitchat to tom;
  1. 列出chitchat数据库中的所有序列:
    SELECT c.relname FROM pg_class c WHERE c.relkind = 'S';
  2. 授予对每个序列的访问权限
    GRANT all privileges on sequence users_id_seq to tom;
    GRANT all privileges on sequence threads_id_seq to tom;
    GRANT all privileges on sequence posts_id_seq to tom;
    GRANT all privileges on sequence sessions_id_seq to tom;
英文:

You can see examples in lib/pq/doc.go or murz/dat (which uses lib/pq):

db, err := sql.Open("postgres", "user=pqgotest dbname=pqgotest sslmode=verify-full")
db, err := sql.Open("postgres", "dbname=dat_test user=dat password=!test host=localhost sslmode=disable")

> You can also connect to a database using a URL. For example:

db, err := sql.Open("postgres", "postgres://pqgotest:password@localhost/pqgotest?sslmode=verify-full")

The OP proposes:

> 1. Grant access to database
GRANT all privileges on database chitchat to tom;
2. List all sequences in chitchat database:
SELECT c.relname FROM pg_class c WHERE c.relkind = 'S';
3. Grant access to each of them
GRANT all privileges on sequence users_id_seq to tom;
GRANT all privileges on sequence threads_id_seq to tom;
GRANT all privileges on sequence posts_id_seq to tom;
GRANT all privileges on sequence sessions_id_seq to tom;

huangapple
  • 本文由 发表于 2015年9月22日 14:26:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/32709804.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定