Thursday, October 13, 2011

Exception in thread "main" java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

if you get below mentioned exceptions while connecting My SQL using JDBC, Just make sure that password and other login credentials are provided correctly.

Exception in thread "main" java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1056)
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3376)
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3308)
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:894)
        at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3808)
        at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1256)
        at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2032)
        at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:729)
        at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:46)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
        at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
        at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:283)
        at java.sql.DriverManager.getConnection(Unknown Source)
        at java.sql.DriverManager.getConnection(Unknown Source)


Solution :

Just make sure that password you provide is correct, Cross check the password you have provided.

Below is the simple JDBC test program, To run this program make sure you add Jar file like mysql-connector-java-5.1.5.jar to classpath.

Make sure you provide all correct login credentials in Step 2. i.e. port, database name and password.
/* Test.java */

import java.sql.*;
public class Test
{
public static void main(String[] args) throws Exception
{
Connection con;
Statement stat;
Class.forName("com.mysql.jdbc.Driver");//Step 1: Loading Drivers

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/Test","root","password");//Step 2: Making Connection

stat=con.createStatement();//Step 3: Creating JDBC Statement

String query = "select * from table_name;";

ResultSet rset=stat.executeQuery(query);//Step 4: Execute the Ststement

while(rset.next())//Step 5: Looping through the ResultSet
{
    System.out.println(rset.getString(1));
}
stat.close();//step 6: Close the Connection and Statement
con.close();
}
}

No comments:

Post a Comment