Vipul Walia Vipul Walia - 3 months ago 6
MySQL Question

How to verify whether localhost username and password is correct or not using java?

I've been looking for verification of localhost(in my case XAMPP) username and password i.e 'root' and '' (null). Suppose user changed localhost username and password then how can we verify that using java + SQL QUERY.

//Database credentials
public static Connection conn = null;
public static Statement stmt = null;
public static String JDBC_DRIVER = "com.mysql.jdbc.Driver";
public static String DB_URL = "jdbc:mysql://localhost/";

Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL);
System.out.println("Driver LOADED");
conn = DriverManager.getConnection( DB_URL , LH_USERNAME , LH_PASSWORD);
stmt = conn.createStatement();


Is there any way i can get Boolean result while executing one of the above

Answer

You can surround

conn = DriverManager.getConnection( DB_URL , LH_USERNAME , LH_PASSWORD);

whit try catch block in this way:

try { conn = DriverManager.getConnection( DB_URL , LH_USERNAME , LH_PASSWORD); } catch(SQLException e){ if(e.getMessage().startsWith("Access denied for user")){ System.out.println("Error: nont valid user or password"); //you can add return false if you want return false; } }