MySQL denied my access from a Java program but not from command line

I installed MySQL on a Ubuntu 14.04 machine. I could login with root from the command line. But when I run the following java program, I received an access denied exception. What was wrong?

import java.sql.Connection;
import java.sql.DriverManager;

public class Conn {
    public static void main(String[] args) throws Exception {
        Connection conn = DriverManager.getConnection("jdbc:mysql://"
            + "localhost" + "/xi_tong?characterEncoding=utf8", "root",

The exception:

Exception in thread "main" java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
    at com.mysql.jdbc.SQLError.createSQLException(
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(
    at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(
    at com.mysql.jdbc.MysqlIO.doHandshake(
    at com.mysql.jdbc.ConnectionImpl.coreConnect(
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(
    at com.mysql.jdbc.ConnectionImpl.createNewIO(
    at com.mysql.jdbc.ConnectionImpl.<init>(
    at com.mysql.jdbc.JDBC4Connection.<init>(
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(
    at java.lang.reflect.Constructor.newInstance(
    at com.mysql.jdbc.Util.handleNewInstance(
    at com.mysql.jdbc.ConnectionImpl.getInstance(
    at com.mysql.jdbc.NonRegisteringDriver.connect(
    at java.sql.DriverManager.getConnection(
    at java.sql.DriverManager.getConnection(
    at Conn.main(

I could login from the command line:

zirui@52:~$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 104
Server version: 5.5.55-0ubuntu0.14.04.1 (Ubuntu)

Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective

Type 'help;' or '\h' for help. Type '\c' to clear the current input 


On another machine:

zirui@45:~/Server/src$ java -cp .:mysql-connector-java-5.1.40-bin.jar Conn

2 answers

  • answered 2017-08-12 10:00 MrViK

    Ensure db exists.

    USE yourdb; 

    I recently had a problem like this where the dbname was wrong typed.

  • answered 2017-08-12 10:47 Zirui Wang

    The problem is with privileges! The problem is with privileges!