I work on an exame system with user login, admin login, etc.
When I check if the entered username (for example)
it doesn't return if it is already in the database
and creates it again!
try{
// Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/big_project_3","root","");
//imporrrrrrrrrrrrrrrrrrrrrrrtant
String selectquery = "select count(*)from uesrs where username='" + username + "'and password='" + password + "'";
Statement stat=con.createStatement();
System.out.println(selectquery);
ResultSet rs=stat.executeQuery(selectquery);
System.out.println(rs.next());
if(rs.next()==true){
infoMessage("Already registered ","Welcom");
}
else{
String insertQuery = "insert into uesrs values(null,'" + username_new_student.getText() + "','" + password_new_student.getText() + "','" + First_name_new_student.getText()+"')";
stat.executeUpdate(insertQuery);
infoMessage("info is inserted ","Alert!!!!!");
dispose();
user_login ul=new user_login();
ul.setLocationRelativeTo(null);
ul.setVisible(true);
}
}
catch (Exception ex) {
System.out.println(ex);
}
Once you call rs.next() inside System.out.println () it will move the pointer forward. Then when you call rs.next() inside if condition there will be no more results to show.
try{
// Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/big_project_3","root","");
//imporrrrrrrrrrrrrrrrrrrrrrrtant
String selectquery="select count(*)from uesrs where username='"+username+"'and password='"+password+"'";
Statement stat=con.createStatement();
System.out.println(selectquery);
ResultSet rs=stat.executeQuery(selectquery);
if(rs.next() ){
infoMessage("Already registered ","Welcom");
}
else{
String insertQuery="insert into uesrs values(null,'"+username_new_student.getText()+"','"+password_new_student.getText()+"','"+First_name_new_student.getText()+"')";
stat.executeUpdate(insertQuery);
infoMessage("info is inserted ","Alert!!!!!");
dispose();
user_login ul=new user_login();
ul.setLocationRelativeTo(null);
ul.setVisible(true);
}
}
catch (Exception ex) {
System.out.println(ex);
}
Related
There are entries in the database but whenever i enter any valid or invalid details in login form it always displays login failed. rs.next() is always returning false. Any solution for this problem ?
Code is as follows:-
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/logindata","root","");
#SuppressWarnings("deprecation")
String sql ="Select * from login Where UserName=' " + textField.getText()+ " 'and Password= ' " + passwordField.getText().toString()+"'";
PreparedStatement stmt =con.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
String id=null;
String userId=null;
while(rs.next())
{
id=rs.getString("UserName");
userId=rs.getString("Password");
}
if(id!=null)
System.out.println("Login Success");
else
System.out.println("Login Failed");
con.close();
}
catch(Exception ex) {
System.out.println(ex);
}
public static ArrayList<User_Database> getUsername() {
ArrayList<User_Database> list_Username = new ArrayList<User_Database>();
try {
Class.forName(driver);
String sql = "SELECT user_name FROM users";
Connection connect = DriverManager.getConnection(url, user, password);
Statement state = connect.createStatement();
ResultSet rs = state.executeQuery(sql);
while (rs.next()) {
String user_name = rs.getString("user_name");
User_Database userDB = new User_Database(user_name);
list_Username.add(userDB);
System.out.printf(" %s \n", user_name);
}
rs.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
return list_Username;
}
public static void createNewUser(User_Database us) {
getAllUser();
try {
Class.forName(driver);
Connection connect = DriverManager.getConnection(url, user, password);
Statement state = connect.createStatement();
String sql = "INSERT INTO users VALUES (0, '" + us.user_name + "' , '" + us.user_password + "' , '"
+ us.email + "') ";
if (getAllUser().equals(us.user_name)) {
System.out.println("Username not available");
} else {
state.executeUpdate(sql);
state.close();
System.out.println("Insert Database Success");
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
}
You're calling getAllUser() and I don't know what is does. Let's suppose that you want to call getUsername() instead, which is the method that you present here and that returns all the usernames that you have in your DB in an ArrayList<User_Database>.
When you do if (getAllUser().equals(us.user_name)) you're trying to compare an ArrayList with a String, which is wrong. Please, find the correction to your code bellow:
public static void createNewUser(User_Database us) {
try {
Class.forName(driver);
Connection connect = DriverManager.getConnection(url, user, password);
Statement state = connect.createStatement();
String sql = "INSERT INTO users VALUES (0, '" + us.user_name + "' , '" + us.user_password + "' , '"
+ us.email + "') ";
boolean isUnique = true;
for(User_Database user: getUsername()) {
if(user.user_name.equals(us.user_name)) {
isUnique = false;
break;
}
}
if (!isUnique) {
System.out.println("Username not available");
} else {
state.executeUpdate(sql);
state.close();
System.out.println("Insert Database Success");
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
}
Other notes
Close your statement outside the try catch block, e.g. inside a finally block. This way you ensure that even in the occurence of an exception it will be closed.
Don't forget to close the connection too.
Try to not directly insert the information given by users in your queries, since it can lead to serious problems in your DB (e.g., SQL Injection). Try to see this and use PreparedStatement instead.
Another important consideration:
Since you're checking for the uniqueness of usernames, an ArrayList might not be the best (in terms of performance) to achieve what you want, since you have to go through it when you want to check if there is already a username in your DB or not (O(N)). Instead, try to get all usernames and put them in a HashSet. With set, you just have to try to add the username to it; you will get a true if username is unique or false if it is already in the set (O(1)).
Hope it helped.
Trying to use JDBC to handle some logic for validating if a user and password are in the DB and correct.
The method should return true if they are in the DB or false if not
I've tried changing the methods and it always either lets any user in, even if they dont exist, or no one in, even if they are in the DB.
Can someone explain how to fix this, funnily enough it was working the other day but I've changed something and unsure what...
JDBC code
public boolean checkUser(String username, String pass) {
boolean valid = false;
try {
//loading drivers for mysql
Class.forName("org.apache.derby.jdbc.ClientDriver");
//creating connection with the database
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/workoutDB", "root", "root");
System.out.println("username = " + username);
System.out.println("pass = " + pass);
String sql = "SELECT * FROM users WHERE (username = '" + username + "' AND password = '" + pass + "')";
System.out.println("lo " + sql);
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery(sql);
out.println(valid);
if(rs.next()) {
valid = true;
out.println(valid);
} else {
valid = false;
}
} catch (ClassNotFoundException | SQLException e) {
out.println(e);
}
out.println(valid);
return valid;
}
I've included an image of the console output, the username test, with password tes is in the db.
Sorry it was another class which does the same thing I added the prepared too, it also always returns true or false regardless of if the condition is met.
public boolean checkUser(String username, String pass) {
boolean valid = true;
try {
//loading drivers for mysql
Class.forName("org.apache.derby.jdbc.ClientDriver");
//creating connection with the database
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/workoutDB", "root", "root");
System.out.println("username = " + username);
System.out.println("pass = " + pass);
//String sql = "SELECT username FROM users WHERE (username = '" + username + "')";
//String sql2 = "SELECT password FROM users WHERE (password = '" + pass + "')";
//System.out.println(sql);
//System.out.println(sql2);
//Statement statement = con.createStatement();
//ResultSet rs = statement.executeQuery(sql);
//ResultSet rs2 = statement.executeQuery(sql2);
PreparedStatement ps = con.prepareStatement("select * from users where username=? and password=?");
ps.setString(1, username);
out.println("ps "+ps);
ps.setString(2, pass);
out.println("ps "+ps);
ResultSet rs = ps.executeQuery();
valid = !rs.next();
} catch (ClassNotFoundException | SQLException e) {
out.println(e);
}
out.println(valid);
return valid;
}
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/supermarket?username=root&password=");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM users WHERE username '" + username + "' AND password = PASSWORD( '" + password + "')");
rs.next();
if (rs.getRow() == 1) {
setVisible(false);
new Home().setVisible(true);
}
else {
jLabelAlarm.setText("Incorrect Username or Password!");
}
} catch (Exception e) {
}
I am new in java. This code belongs to login for connecting to MySQL server, but after running it not works properly.
("jdbc:mysql://localhost:3306/supermarket/root, "");
Just change the database connection code to this type.
I am trying to select data from a table using prepared statement. But it seems like I am getting syntax error which I cannot solve alone.
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb";
String dbusername = "root";
String dbpassword = ""; // Change it to your Password
// Setup the connection with the DB
connection = DriverManager.getConnection(url, dbusername,
dbpassword);
String query = "SELECT * FROM admin WHERE username = ? AND password = ?";
try {
// connection.setAutoCommit(false);
selectUser = connection.prepareStatement(query);
selectUser.setString(1, username);
selectUser.setString(2, password);
// Execute preparedstatement
ResultSet rs = selectUser.executeQuery(query);
// Output user details and query
System.out.println("Your user name is " + username);
System.out.println("Your password is " + password);
System.out.println("Query: " + query);
boolean more = rs.next();
// if user does not exist set the validity variable to true
if (!more) {
System.out
.println("Sorry, you are not a registered user! Please sign up first!");
user.setValid(false);
}
// if user exists set the validity variable to true
else if (more) {
String name = rs.getString("name");
System.out.println("Welcome " + name);
user.setName(name);
user.setValid(true);
}
} catch (Exception e) {
System.out.println("Prepared Statement Error! " + e);
}
} catch (Exception e) {
System.out.println("Log in failed: An exception has occured! " + e);
} finally {
}
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
System.out.println("Connection closing exception occured! ");
}
connection = null;
}
return user;
}
I get following error.
Prepared Statement Error! com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? AND password = ?' at line 1
But I don't see any error in that code line.
Change
ResultSet rs = selectUser.executeQuery(query);
to
ResultSet rs = selectUser.executeQuery();
when you already prepared the statement in connection.prepareStatement(query); then why to pass the query again in selectUser.executeQuery(query);
what you want to do is use this method
ResultSet rs = selectUser.executeQuery();
You have already loaded your query inside the prepared statement here ,
selectUser = connection.prepareStatement(query);
so execute it by ,
ResultSet rs = selectUser.executeQuery();
Also read ,
How does PreparedStatement.executeQuery work?