你不应该使用executeQuery()
方法executeUpdate()
statement = connect.createStatement();
statement.executeQuery("SET PASSWORD FOR 'username'@'localhost' = PASSWORD('123456')");
请注意,使用上述查询只能更改已知密码。
例如,如果 root 密码example
用于创建我们使用的连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "example");
因此,使用此连接我们只能更改当前密码。
以下是基于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();
}
}
}
所以现在新的mysql root密码是test