英文:
error connecting to database with mysqldriver
问题
我正在尝试按照这里的说明https://github.com/go-sql-driver/mysql#installation和http://go-database-sql.org/accessing.html创建一个sql.db。
我的代码的第一行是这样的:
db, err := sql.Open("mysql", "username@localhost/my_db")
当我在终端上运行程序时,我得到了这个错误:
Default addr for network 'localhost' unknown
为什么会这样?当我检查mysql的用户和主机时,它显示为'username'和'localhost'。我按照以下参数进行了设置:
[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...¶mN=valueN]
英文:
I'm trying to follow the instructions here https://github.com/go-sql-driver/mysql#installation and http://go-database-sql.org/accessing.html to create a sql.db.
The first line of my code has this
db, err := sql.Open("mysql", "username@localhost/my_db")
When I ran the program on the terminal, I got this:
Default addr for network ''localhost'' unknown
Why is this? When I checked the user and host to mysql it states 'username' and 'localhost'. I followed the parameters like this:
[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...&paramN=valueN]
答案1
得分: 126
你可能想要指定协议(比如'tcp'),而不是直接使用localhost
。参见这些示例:
user:password@tcp(localhost:5555)/dbname
在你的情况下:
username@tcp(localhost)/my_db
注意,如果你使用默认的协议(tcp
)和主机(localhost:3306
),可以将其重写为
user:password@/dbname
Lakshminarayanan Guptha在评论中补充道:
> 在我的情况下,- user:password@tcp/dbname
可以工作
英文:
You might want to specify the protocol (like 'tcp
'), instead of localhost
directly.
See those examples:
user:password@tcp(localhost:5555)/dbname
In your case:
username@tcp(localhost)/my_db
Note, if you use the default protocol (tcp
) and host (localhost:3306
), this could be rewritten as
user:password@/dbname
Lakshminarayanan Guptha adds in the comments:
> In my case - user:password@tcp/dbname
worked
答案2
得分: 2
我遇到了同样的问题,而且得票最多的答案对我没有帮助。救了我一命的是将(host:port)
放在引号中,即"(host:port)"
。
英文:
I had the same problem and the most voted answer couldn't help me. What saved me was putting (host:port)
inside quotation --> "(host:port)"
答案3
得分: 0
我在我的Linux虚拟机上运行Docker容器时遇到了类似的问题。在我的应用程序(server.go
)中,我将localhost的值更改为使用我的虚拟机的IP,然后成功构建和运行了容器。
mysql容器(3307)<--> [(应用程序mysql:<虚拟机IP>:3307)容器](暴露3000) <--> 世界
英文:
I had faced a similar issue as I was running Docker containers on my Linux VM. In my application (server.go
) I changed the localhost value to use the IP of my virtual machine and then build and ran the container successfully.
mysql container (3307) <--> [(application mysql:<vm ip>:3307) container](expose 3000) <--> world
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论