Home > Back-end >  how to write correct dsn in linux
how to write correct dsn in linux

Time:10-15

i follow this tutorial https://golang.org/doc/tutorial/database-access and i don't know how to connect to mysql in code just to know i done all this: Create a folder for your code, Set up a database, Find and import a database driver

and my problem in this step Get a database handle and connect https://golang.org/doc/tutorial/database-access#get_handle

the code

// Capture connection properties.
cfg := mysql.Config{
    User:                 "hashem",
    Passwd:               "hashem",
    Net:                  "tcp",
    Addr:                 "127.0.0.1:3306",
    DBName:               "recordings",
    AllowNativePasswords: true,
}
// Get a database handle.
println(cfg.FormatDSN())
var err error
db, err = sql.Open("mysql", cfg.FormatDSN())
if err != nil {
    log.Fatal(err)
}

pingErr := db.Ping()
if pingErr != nil {
    log.Fatal(pingErr)
}
fmt.Println("Connected!")

in this code it should print Connected! but it always return errors Error 1045: Access denied for user 'hashem'@'localhost' (using password: YES) the user name and password and localhost i think it is correct. and just to know when i login in mysql in the terminal sudo mysql -u root -p and require the linux password and i type hashem and then require mysql password and i don't type any things here and its login very well and i can do every things well like select and insert. but in the code i can't login

CodePudding user response:

The issue is with the mysql user login. Few steps to break your issue down.

  1. If you have created the user and password already, login and check if you have granted the required privileges.
$ mysql -u hashem -p
mysql> SHOW GRANTS FOR 'hashem'@'localhost';

If you are not sure, grant all privileges:

$ sudo mysql -u root
mysql> GRANT ALL PRIVILEGES ON * . * TO 'hashem'@'localhost';
mysql> FLUSH PRIVILEGES;
  1. Check if you have created the required database.
$ mysql -u hashem -p
mysql> CREATE DATABASE recordings;
Query OK, 1 row affected (0.96 sec)
  1. Check if the connection string is being generated in the way you want it to be. Print cfg.FormatDSN() before connecting and check.
username:password@tcp(127.0.0.1:3306)/database?allowNativePasswords=false&checkConnLiveness=false&maxAllowedPacket=0

By your comment, the allowNativePasswords is not mentioned in your connection string. For more info on this, check page@Medium

References:

  1. https://www.digitalocean.com/community/tutorials/how-to-create-a-new-user-and-grant-permissions-in-mysql
  2. https://www.inmotionhosting.com/support/server/databases/create-a-mysql-database/
  3. https://medium.com/@crmcmullen/how-to-run-mysql-8-0-with-native-password-authentication-502de5bac661
  • Related