skip to Main Content

I created a user ‘gou’ for all my golang projects.

create user 'gou'@'localhost' identified by 'gop';
grant select, insert, update, delete, create, drop, alter on gdb.* to 'gou'@'localhost';

This is the code in go:

...
_ "github.com/go-sql-driver/mysql"
...


db, err := sql.Open("mysql", "gou:gop@tcp(localhost:3306)/gdb?parseTime=true")

When I run the code I am getting (IP omitted):

Error 1045 (28000): Access denied for user 'gou'@'my.very.own.ip' (using password: YES) exit status 1

Note: I can actually run the code:

  • using root user, but I don’t want to use root
  • useing user ‘gou’@’%’, but I only want to access from localhost

2

Answers


  1. set password for user gou and access your database using

    cfg := mysql.Config{
    User: gou,
    Passwd: password,
    Net: "tcp",
    Addr: "127.0.0.1:3306",
    DBName: "dbname", }

    db, err = sql.Open("mysql", cfg.FormatDSN())
    if err != nil { log.Fatal(err) }

    Login or Signup to reply.
    1. Create a password for your mysql user, then:
    //Or maybe this line works good too:
    const (
        host = "localhost"
        port = 8080
    
        dbUser = "myUser"
        dbPass = "myPassOfMysql"
        dbHost = "localhost"
        dbPort = "3306"
        dbName = "MyDBName"
    )
    mysqlURI := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", dbUser, dbPass, dbHost, dbPort, dbName)
        db, err := sql.Open("mysql", mysqlURI)
        if err != nil {
            log.Fatal(err)
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search