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

Sign up to request clarification or add additional context in comments.

14 Comments

You need to use executeUpdate() only for any Insert, Update or Delete query.
@R.J yes true but for this case executeQuery should be used
Credit is required; plagiarism not allowed! Why did you rollback my edit?
Again, why did you remove the attribution?
Do not roll back the attribution of the source of your code. This is your last warning.
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.