For example, I've got MySQL table with all users data
How to make after user sign in, he sees his own username?
I've tried this:
con = DriverManager.getConnection(url, user, password);
stmt = con.createStatement();
rs = stmt.executeQuery(query);
while (rs.next()) {
String name = rs.getString(1);
System.out.println("username : " + name);
}
But it just shows all usernames in MySQL table.
Your query does not filter the rows of the table.
Use a WHERE clause:
String query = "select username from users where username = ?";
stmt.setString(1, user);
rs = stmt.executeQuery(query);
if (rs.next()) {
String name = rs.getString(1);
System.out.println("username : " + name);
} else {
System.out.println("No user : " + user);
}
The ? placeholder will be replaced by the value of the variable user properly quoted.
String query = "select username from users";
to
String query = "select username from users where username = '"+user+"' ";
To avoid sql injections, it is advisable to use a PreparedStament. Check this link for more details: https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html