TLDR; Error attempting to access DB with Golang
I am trying to connect to my localhost db using the example here. The go code for connecting to the DB can be found below.
func main() {
// Capture connection properties.
cfg := mysql.Config{
User: os.Getenv("DBUSER"),
Passwd: os.Getenv("DBPASS"),
Net: "tcp",
Addr: "127.0.0.1:3306",
DBName: "someDB",
}
// 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!")
}
I see the this output
✗ go run main.go
2023/02/17 00:10:35 Error 1045 (28000): Access denied for user 'root'#'localhost' (using password: YES)
I have tried:
confirmed that DBUSER and DBPASS are set with the expected value
I am able to mysql -u root -p and connect to DB without any issues.
The solution to my problem was solved by updating my password. My password started with #. After I updated my password.
mysql -u root -h localhost -p
mysql> ALTER USER 'root'#'localhost' IDENTIFIED BY 'some-new-password';
mysql> FLUSH PRIVILEGES;
Now when I run my code I see Connected!
Related
I am new to golang, docker and mysql. I am trying to connect to mysql running in docker locally on my macos using golang.
Here is the code:
`package main
import (
"context"
"database/sql"
_ "github.com/go-sql-driver/mysql"
"log"
"time"
)
func dbConn() *sql.DB {
db, err := sql.Open("mysql", "root:Abc123$##tcp(172.17.0.2:3306)/test")
if err != nil {
log.Printf("Error %s when opening DB connection\n", err)
return nil
}
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(10)
db.SetConnMaxLifetime(time.Minute * 2)
ctx, cancelfunc := context.WithTimeout(context.Background(), time.Second)
defer cancelfunc()
err = db.PingContext(ctx)
if err != nil {
log.Printf("Error %s pinging DB", err)
return db
}
log.Print("Connected to the DB successfully\n")
defer func() {
err := db.Close()
if err != nil {
log.Print(err)
}
}()
return db
}
func main() {
db := dbConn()
defer db.Close()
}`
I am running docker with the following command:
docker run --name mysql -e MYSQL_ROOT_PASSWORD=abcd1234 -p 3306:3306 -d mysql:8.0.30
I get the following error:
Error dial tcp 172.17.0.2:3306: i/o timeout pinging DB
docker is running locally. I created a test-db with command-line:
`mysql> create database test_db;`
and then did a
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
| test_db |
+--------------------+
6 rows in set (0.00 sec)
Please help me understand my mistake here? Or what am I missing?
I used host.docker.internal in this docker-compose.yml file to create the mysql sever in docker.
version: '3'
services:
mysql-development:
image: mysql:8.0.30
environment:
MYSQL_ROOT_PASSWORD: xyz1234
MYSQL_DATABASE: test
ports:
- "3306:3306"
extra_hosts:
- "host.docker.internal:host-gateway"
Used this to run the docker image:
docker-compose -f docker-compose.yml up
Then connected to docker mysql instance using:
docker exec -it 24f058c73227 mysql -P 3306 --protocol=tcp -u root -p
Then created a separate user and granted all privileges to the new user.
mysql> CREATE user ‘user2’#‘172.19.0.1' IDENTIFIED BY ‘xyz1234’;
mysql> GRANT ALL PRIVILEGES ON *.* TO 'user2'#'172.19.0.1' WITH GRANT
OPTION;
This helped me connect to mysql server running on the docker locally on macos.
When I do Repo.start_link with incorrect credential I got state :ok
{state, pid} =
MyApp.Repo.start_link(
name: nil,
hostname: hostname,
username: username,
password: password,
database: db_name,
pool_size: 1
)
state and pid = {:ok, #PID<0.551.0>}
But in the logs I got
[error] MyXQL.Connection (#PID<0.554.0>) failed to connect: ** (MyXQL.Error) (1045) (ER_ACCESS_DENIED_ERROR) Access denied for user 'username'#'localhost' (using password: YES)
How I can get error message in {state, pid}?
You can start another Repo without a name, but you can't access it directly, all operations are sent to the default repository Myapp.Repo.
You can also start repositories without names by explicitly setting
the name to nil:
MyApp.Repo.start_link(name: nil, hostname: "temp.example.com")
However, once the repository is started, you can't directly interact with
it, since all operations in MyApp.Repo are sent by default to the repository named MyApp.Repo.
Source: https://github.com/elixir-ecto/ecto/blob/v3.6.2/lib/ecto/repo.ex#L554
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';
I encountered a very strange phenomenon about Spring boot and use mysql to store data, today in my private computer I git cloned my developing project. When run the entry main class in eclipse, it throws exception
2015-11-15 18:28:08.912 ERROR 9183 --- [ restartedMain] o.a.tomcat.jdbc.pool.ConnectionPool : Unable to create initial connections of pool.
java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:998) ~[mysql-connector-java-5.1.36.jar:5.1.36]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847) ~[mysql-connector-java-5.1.36.jar:5.1.36]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783) ~[mysql-connector-java-5.1.36.jar:5.1.36]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:871) ~[mysql-connector-java-5.1.36.jar:5.1.36]
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1665) ~[mysql-connector-java-5.1.36.jar:5.1.36]
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1207) ~[mysql-connector-java-5.1.36.jar:5.1.36]
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2249) ~[mysql-connector-java-5.1.36.jar:5.1.36]
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2280) ~[mysql-connector-java-5.1.36.jar:5.1.36]
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2079) ~[mysql-connector-java-5.1.36.jar:5.1.36]
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:794) ~[mysql-connector-java-5.1.36.jar:5.1.36]
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44) ~[mysql-connector-java-5.1.36.jar:5.1.36]
it's application.properties :
spring.datasource.url = jdbc:mysql://localhost:3306/foo?useUnicode=true&characterEncoding=utf8
spring.datasource.username = root
spring.datasource.password = 123456
but I could login mysql directly in terminal, see below:
mysql -hlocalhost -uroot -p123456
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 50
Server version: 5.6.27-0ubuntu0.14.04.1 (Ubuntu)
and I even write a sample java code in the same project to test connection with local mysql server,
public static void main(String[] args) throws SQLException {
String url = "jdbc:mysql://localhost:3306/foo?useUnicode=true&characterEncoding=utf8";
String user = "root";
String password = "123456";
Connection connection = DriverManager.getConnection(url , user , password);
System.out.println(connection);
Statement stat = connection.createStatement();
ResultSet rs = stat.executeQuery("select version()");
rs.next();
System.out.println(rs.getString(1));
}
Run it have normal output:
com.mysql.jdbc.JDBC4Connection#48cf768c
5.6.27-0ubuntu0.14.04.1
So why spring-boot can't connect to local mysql server, but other ways could?
I have the weirdest MySQL login problem ever!
The DBMS is installed on my desktop and I'm accessing it locally, not through a network or internet.
When I try to connect to it via cmd:
mysql -u root -proot;
it connects perfectly..
but, when I try to connect through a Java program in NetBeans:
Connection con = null;
String url ="jdbc:mysql://localhost:3306/testdb";
String user ="root";
String password ="root";
try
{
con = DriverManager.getConnection(url,user,password);
}
Catch(Exception e)
{
System.out.println(e.toString() );
}
it throws an exception !!
java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)
I have the mysql-connector-java-5.1.24-bin.jar library added to NetBeans..
It was working before, not sure why it is not working now!!
Also, when I connect to MySQL like this:
mysql -u root -p;
then I enter the password, it gives this error:
ERROR 1045 (28000): Access denied for user 'root'#'localhost' (using password: YES)
??
Connection con = null;
String dbase = "database";
String dbuser = "root";
String dbpass = "";
try{
String ConnString;
Class.forName("com.mysql.jdbc.Driver").newInstance();
ConnString = "jdbc:mysql://localhost:3306/"+dbase+"?user="+dbuser+"&password="+dbpass;
con = DriverManager.getConnection(ConnString);
//System.out.println("Connection to database successful!");
}catch(Exception e){
e.printStackTrace();
}
Try this?
so stupid ~~~
I found the problem ...
Here's why this is happening and how I solved it:
Reason of problem: I changed the password for root from blank to 'root'
Then, I couldn't connect to MySQL from Java ..
it turns out I have to update the privileges of the database after changing the password.
So I did that by:
GRANT ALL PRIVILEGES ON [database_name].* to '[user]'#'[hostname]' identified by '[password]'
and now it works 100%