登录
首页 >  Golang >  Go问答

无法使用 go-sql-driver 连接 MariaDB,尽管 mariadb-client 可以连接

来源:stackoverflow

时间:2024-03-21 09:09:32 185浏览 收藏

在 Debian 10 Linux 服务器上安装了 MariaDB 10.3 和 Galera 集群后,使用 mariadb-client 能够连接数据库,但使用 go-sql-driver/mysql 却出现“访问被拒绝”错误。问题原因可能是连接字符串不正确,可能使用了错误的协议或端口。

问题内容

我已经在 debian 10 linux 服务器上安装了 mariadb 10.3 和 galera 集群。

我创建了一个用户ueda并授予所有权限,如下所示:

mariadb [koshinto]> show grants for 'ueda'@'localhost';
+----------------------------------------------------------------------------------------------------------------------------------------+
| grants for ueda@localhost                                                                                                              |
+----------------------------------------------------------------------------------------------------------------------------------------+
| grant all privileges on *.* to `ueda`@`localhost` identified by password '*923d7e4a76755e0b4924c29266afa3e675d990dc' with grant option |
+----------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.000 sec)

我可以使用用户ueda登录并发出sql命令,如下所示:

ueda@scw-a:~$ mariadb -u ueda -p
enter password: 
welcome to the mariadb monitor.  commands end with ; or \g.
your mariadb connection id is 169
server version: 10.3.27-mariadb-0+deb10u1 debian 10

copyright (c) 2000, 2018, oracle, mariadb corporation ab and others.

type 'help;' or '\h' for help. type '\c' to clear the current input statement.

mariadb [(none)]> use koshinto
reading table information for completion of table and column names
you can turn off this feature to get a quicker startup with -a

database changed
mariadb [koshinto]> select * from test;
+----------+------------------------------+
| bindid   | bind                         |
+----------+------------------------------+
| kerokero | {"kero":"kerokero","aho":20} |
+----------+------------------------------+
1 row in set (0.001 sec)

但是,从下面的代码来看,

package main

import (
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
    "log"
)

func main() {
    log.setflags(log.lshortfile)
    db, err := sql.open("mysql", "ueda:somepassword@/koshinto")
    defer db.close()
    if err != nil {
        log.println(err)
    } else {
        _, err := db.query("select * from test") //
        if err != nil {
            log.println(err)
        }
    }
}

即使在同一服务器上使用相同的用户名和密码,也会出现“访问被拒绝”的错误。

ueda@scw-a:~$ go run mysql.go 
mysql.go:18: Error 1045: Access denied for user 'ueda'@'localhost' (using password: YES)

解决方案


您使用的连接字符串正确吗?不确定您是否掩盖了代码片段中的某些内容,但请确保使用 ueda:somepassword@protocol(ip:port)/koshinto 当您运行时,它很可能是 ueda:somepassword@tcp(localhost:3306)/koshinto同一台机器

到这里,我们也就讲完了《无法使用 go-sql-driver 连接 MariaDB,尽管 mariadb-client 可以连接》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

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