user3918985
user3918985

Reputation: 4409

error connecting to database with mysqldriver

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]

Upvotes: 56

Views: 31273

Answers (3)

VonC
VonC

Reputation: 1323303

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

Upvotes: 134

nevosial
nevosial

Reputation: 1144

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 

Upvotes: 0

raha
raha

Reputation: 31

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)"

Upvotes: 3

Related Questions