1

I'm trying to change a user's password on mysql using java, i successfully changed it on phpmyadmin but same command doesnt work on java

SET PASSWORD = PASSWORD('12345')

this command will change the current logged in user, i have tried it on java like this

statement = connect.createStatement();
statement.executeUpdate("SET PASSWORD = PASSWORD('12345')");

but nothing happened

i also tried this with root logged in

statement = connect.createStatement();
statement.executeUpdate("SET PASSWORD FOR 'username'@'localhost' = PASSWORD('123456')");

and nothing work,, any help please

1 Answer 1

1

you should use executeQuery() method not executeUpdate()

statement = connect.createStatement();
statement.executeQuery("SET PASSWORD FOR 'username'@'localhost' = PASSWORD('123456')");

Note only known password can be changed using the above query.

for example if root password is example then for creating connection we use

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "example");

So using this connection we can only change present password.

The following is an example based on this code at roseindia.net:

import java.sql.*;
class ChangeRootPassword
{
        public static void main(String[] args) 
        {
                try{
                        Class.forName("com.mysql.jdbc.Driver");
                        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "example");
                        String sql = "SET PASSWORD FOR 'root'@'localhost' = PASSWORD('test')";
                        Statement stmt = conn.createStatement();
                        stmt.executeQuery(sql);
                        stmt.close();
                        conn.close();
                        System.out.println("Password is changed successfully!");
                        }
                catch(Exception ex){
                        ex.printStackTrace();
                        }
        }
}

So the new mysql root password now is test

14
  • You need to use executeUpdate() only for any Insert, Update or Delete query.
    – Rahul
    Nov 2, 2013 at 9:39
  • @R.J yes true but for this case executeQuery should be used Nov 2, 2013 at 9:40
  • 3
    Credit is required; plagiarism not allowed! Why did you rollback my edit?
    – Arjan
    Nov 2, 2013 at 14:08
  • 1
    Again, why did you remove the attribution?
    – Arjan
    Nov 16, 2013 at 12:41
  • 5
    Do not roll back the attribution of the source of your code. This is your last warning.
    – Brad Larson
    Nov 16, 2013 at 16:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.