How do I connect to a MySQL instance without using the password? - mysql

I trying to connect db I have set no password for the db I am leaving blank in the password field. But it's not connecting and showing error connector.go:95: could not use requested auth plugin 'mysql_native_password': this user requires mysql native password authentication.. Also I am using phpmyadmin as db so how to connect here is my code
package main
import (
"database/sql"
"fmt"
"log"
"github.com/go-sql-driver/mysql"
)
var db *sql.DB
func main() {
// Capture connection properties.
cfg := mysql.Config{
User: "root",
Passwd: "",
Net: "tcp",
Addr: "127.0.0.1:3306",
DBName: "recordings",
}
// Get a database handle.
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!")
}

That looks a lot like the code from the Tutorial: Accessing a relational database which unfortunately does not work. You need to specify AllowNativePasswords: true for it to work. That value is true by default, but the defaults are only applied if you use NewConfig() and not create the Config struct yourself. But this will work as well:
cfg := mysql.Config{
User: "root",
Passwd: "",
Net: "tcp",
Addr: "127.0.0.1:3306",
DBName: "recordings",
AllowNativePasswords: true,
}

Try to change authentication plugin of root user to mysql_native_password in your database. More information about here
UPDATE mysql.user SET plugin = 'mysql_native_password' WHERE user = 'root' AND plugin = 'unix_socket';

Related

Go Mysql connection refused due to a burst of connections

Go version 1.18. MySQL server is version 8. System is 2018 MacBook Pro i9 6-cores, 32GB RAM.
However, mysql connection is refused during mysql.QueryRow(). error message is:
panic: dial unix /tmp/mysql.sock: connect: connection refused
PLEASE NOTE: I already find root cause(see my comment in the following code) and have a solution(using semaphore).
I MUST use socket instead of localhost when setting db connection.
The root cause is 2000 Go routines try to send query to MySQL simultaneously. How to solve this problem? My solution is to use semaphore to limit the number of concurrent go-routines, for example 100. I have tested, semaphore solution works well. I actually do not want to use semaphore to limit the number of concurrent mysql queries.
Question: why I can not have 2000 go-routines sending query at the same time.
import (
"database/sql"
mysqlDriver "github.com/go-sql-driver/mysql"
)
type SomeStruct struct {
a string
b string
}
func main() {
cfg := mysqlDriver.Config{
User: "DB_USER",
Passwd: "DB_USER",
Net: "unix",
Addr: "/tmp/mysql.sock", // MySQL is installed on local
DBName: "databaseName",
}
mysql, err := sql.Open("mysql", cfg.FormatDSN())
if err != nil {
panic(err) // tested, panic is not caused here.
}
mysql.SetMaxOpenConns(5000)
mysql.SetMaxIdleConns(5000)
if err = mysql.Ping(); err != nil {
panic(err) // tested, panic is not caused here.
}
var wg sync.WaitGroup
for i := 0; i < 2000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
var someStructVar SomeStruct
err := mysql.QueryRow("select a, b from table where id = ?", i).Scan(&someStructVar.a, &someStructVar.b)
if err != nil {
panic(err) // this is where the panic happens.
}
}
}
wg.Wait()
}
my.cnf is:
[mysqld]
max_connections=5000
connect_timeout=300
If your panic error occur before code
mysql.SetMaxOpenConns(5000)
Then the error is when connecting to the database, try changing the connection configuration to the database

allowCleartextPasswords=1 to DSN

I'm attempting to connect to my local DB via a mysql connection to initiate and run a query off of my database via Go.
When attempting to connect, I am met with this error:
this user requires clear text authentication. If you still want to use it, please add allowCleartextPasswords=1' to your DSN
My Db connection looks like the following: db, err := sql.Open("sql", "<username>:<password>#tcp(127.0.0.1:<port>)/<dbname>?charset=utf8" )
Where can I include this dependency for cleartext authentication?
Since you mentioned you're using MySQL I recommend leveraging the native struct mysql.Config like so:
loc, _ := time.LoadLocation("America/Chicago") // handle any errors!
c := mysql.Config{
User: "user",
Passwd: "pa55w0rd",
Net: "tcp",
Addr: "127.0.0.1:3306",
DBName: "dbname",
Params: map[string]string{"charset": "utf8"}, // extra params
AllowCleartextPasswords: true,
ParseTime: true, // demo option
Loc: loc, // demo option
}
fmt.Println(c.FormatDSN())
It will properly format the DSN string for you - escaping any sensitive character values along the way (e.g. the loc value):
user:pa55w0rd#tcp(127.0.0.1:3306)/dbname?allowCleartextPasswords=true&allowNativePasswords=false&loc=America%2FChicago&parseTime=true&maxAllowedPacket=0&charset=utf8
Playground Example

Go MySQL with SSL - unexpected EOF

I'm using the Go MySQL driver as part of a project. Recently, there was a need to enable SSL on the MySQL database I am connecting to. I have two servers that are configured with TLSv1.1. On one server, I am able connect successfully, but on the other I am getting unexpected EOF from the library.
I tried setting MaxIdleConnections to 0 as described in Golang MySQL error - packets.go:33: unexpected EOF, but no luck. Prior to enabling SSL, connections to the server were working. There are other apps not written in Go that are able to connect successfully using the same credentials.
When my app runs, the ping command fails immediately. The MySQL server logs are saying bad handshake. Is there something off with my connection code below, or is there a database setting that could be refusing to connect with skip-verify?
import (
"database/sql"
"io/ioutil"
"strings"
"text/template"
log "github.com/sirupsen/logrus"
// Import runtime for MySQL
mysql "github.com/go-sql-driver/mysql"
)
type DatabaseConnection struct {
Hostname string
Port int
Database string
Username string
Password string
}
func CreateSSLConnection(db *DatabaseConnection) (*sql.DB, error) {
templateString := `{{.Username}}:{{.Password}}#{{.Hostname}}:{{.Port}}/{{.Database}}?tls=skip-verify`
conn, err := connectToDatabase("mysql", templateString, db)
// error: "unexpected EOF"
err = conn.Ping()
return conn, err
}
func connectToDatabase(databaseType string, connectionTemplateString string, db *DatabaseConnection) (*sql.DB, error) {
connectionTemplate := template.Must(template.New("connectionString").Parse(connectionTemplateString))
builder := strings.Builder{}
err := connectionTemplate.Execute(&builder, db)
if err != nil {
log.WithFields(log.Fields{
"template": connectionTemplateString,
"error": err,
}).Error("Failed to create connection string")
return nil, err
}
return sql.Open(databaseType, builder.String())
}

Can't connect to remote MySql in Go

I need to connect to a remote MySql server using Go. I'm using following code to connect to MySql via gorm.
type DBController struct {
DB gorm.DB
}
func (dc *DBController) InitDB() {
var err error
host := v.GetString("db.mysql.host")
port := v.GetString("db.mysql.port")
user := v.GetString("db.mysql.user")
pass := v.GetString("db.mysql.pass")
db := v.GetString("db.mysql.db")
//user:password#tcp(localhost:5555)/dbname
conn := fmt.Sprintf("%s:%s#tcp(%s:%s)/%s", user, pass, host, port, db)
//conn := v.GetString($user+":"$pass+"#tcp("+$host+":"+$port+")/"+$db)
log.Debug(conn)
dc.DB, err = gorm.Open("mysql", conn)
if err != nil {
log.Fatalf("Error when connect database, the error is '%v'", err)
}
dc.DB.LogMode(true)
}
func (dc *DBController) GetDB() gorm.DB {
return dc.DB
}
When I run the Go server I'm getting following errors
No configuration file loaded - using defaults
:#tcp(:)/
Error when connect database, the error is 'dial tcp: unknown port tcp/'
exit status 1
How can fix this error?
I'm guessing "v" is your config variable… Which contains no data, this is not a problem with Gorm, it's because dc.Open() is not receiving the config values.
If you try to run it with static data, it should work.

mysql error Access denied for user with go-sql-driver when used in separate package

I am getting the following error when using with go-sql-driver with mysql and gorp when using in a separate package called dbutil
Error 1045: Access denied for user 'root'#'localhost' (using password: NO)
package dbutil
import (
"cropz/structs"
"database/sql"
"github.com/coopernurse/gorp"
_ "github.com/go-sql-driver/mysql"
"log"
)
func InitDB() *gorp.DbMap {
// connect to db
db, err := sql.Open("mysql", "root:pass#tcp(127.0.0.1:3306)/jsl")
defer db.Close()
err = db.Ping()
checkErr(err, "Ping failed")
// construct a gorp DbMap
dbmap := &gorp.DbMap{Db: db, Dialect: gorp.MySQLDialect{"InnoDB", "UTF8"}}
return dbmap
}
package main
func main() {
dbmap := dbutil.InitDB()
err := dbmap.Db.Ping()
checkErr(err, "Ping failed")
}
If I have the initDB() function in the main package, it works fine.
This happens only if used with martini framework and dbutil in separate package. With martini framework and in the same package it still works.
I am using windows, MySQL-5.0.22. Please help.
thanks,
Krishna
Your error looks like a login failure. Is your DSN setup appropriately?
Other than that you should remove the defer db.Close()
I believe you should only be closing the Db when you are actually done with it according to the spec.
When I run your code I actually get this error
panic: sql: database is closed
I deleted the .a files generated in the pkg folder and then didn't get the access denied error.