Osama Abukmail
Osama Abukmail

Reputation: 41

changing mysql password via java

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

Upvotes: 1

Views: 3718

Answers (1)

SpringLearner
SpringLearner

Reputation: 13844

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

Upvotes: 1

Related Questions