In this example I want to check if eMail is registered or not. The function checkDuplicateEmail.emailCheck(emailcounter, email) will check the condition and return the boolean value. If the value is not true then it is supposed to insert the data but unfortunately it's not happening. Only in case eMail is matched the the else part is executing.
PreparedStatement st1 = conn.prepareStatement("SELECT * FROM customer where email = ?");
st1.setString(1,email);
ResultSet rs = st1.executeQuery();
checkDuplicateEmail checkDuplicateEmail = new checkDuplicateEmail();
while(rs.next()) {
emailcounter = rs.getString("email");
boolean isValid = checkDuplicateEmail.emailCheck(emailcounter, email);
}
if(!isValid) {
System.out.println("Email is Exists");
PreparedStatement st = conn.prepareStatement("insert into customer(name, email, mobileno, username, password) values(?, ?, ?, ?, ?)");
st.setString(1, name); //substituting ? with actual value
st.setString(2, email);
st.setInt(3, mobileNo);
st.setString(4, username);
String encoded = enc.encodeToString(password.getBytes());
st.setString(5, encoded);
st.executeUpdate();
conn.close();
}
else {
System.out.println("Email is already Exists");
PrintWriter out = response.getWriter();
out.write("<html><body>");
out.write("<h1>Registration cannot be sucessful because email is already registered!</h1>");
out.write("</body></html>");
}
Related
I'm trying to make a register page into my servlet project.
If the username is already taken, I want to show an error message.
Heres my code :
String uname=request.getParameter("uname");
String pass=request.getParameter("pass");
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/covid","root","fbfbfb333*");
String query = "SELECT * FROM users WHERE username = ?";
pstmt = (PreparedStatement) con.prepareStatement(query);
pstmt.setString(1, uname);
rs = pstmt.executeQuery();
if(rs.next()) {
PreparedStatement pst = (PreparedStatement) con.prepareStatement(" insert into users(username,password) values(?,?)");
pst.setString(1, uname);
pst.setString(2, pass);
pst.executeUpdate();
response.sendRedirect("login.jsp");
} else {
System.out.println("Username " + uname + " already exists.");
}
} catch (Exception e) {
e.printStackTrace();
}
But when I add a new users , it says " username already taken " whether it exist or not.
What should I do?
Switch the condition, if there is a result set data means that the username is taken, else insert new username
if(rs.next()) {
System.out.println("Username " + uname + " already exists.");
} else {
PreparedStatement pst = (PreparedStatement) con.prepareStatement(" insert into users(username,password) values(?,?)");
pst.setString(1, uname);
pst.setString(2, pass);
pst.executeUpdate();
response.sendRedirect("login.jsp");
}
I am trying register page, if email exits already it should get alert message, for this below is my some part of the code, i am using executeQuery for Select query but still i am getting error:
java.sql.SQLException: Can not issue executeUpdate() or executeLargeUpdate() for SELECTs
java code:
Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/xxxx", "root","root");
PreparedStatement ps=cn.prepareStatement("select * from Register where email=?");
ps.setString(1, email);
ResultSet rs=ps.executeQuery();
if(rs.next())
{
out.println("<script type=\"text/javascript\">");
out.println("alert('Email already Exists Please Try with New Email');");
out.println("location='index.html';");
out.println("</script>");
}
else{
PreparedStatement ps1 = cn.prepareStatement("insert into Register values(?,?,?,?,?)");
ps1.setString(1, name);
ps1.setString(2, email);
ps1.setString(3, mobile);
ps1.setString(4, password);
ps1.setString(5, conform_password);
int i = ps.executeUpdate();
if (i != 0) {
response.sendRedirect("index.html");
} else {
out.println("Some Thing went wrong. Try Again...");
}
}
}
My guess is that the problem has to do with your not closing the first statement used for the select before you try to create another statement for the insert. But, there is a better way to implement your logic, using a single insert:
String sql = "INSERT INTO Register (name, email, mobile, password, confirm_password) ";
sql += "SELECT ?, ?, ?, ?, ? ";
sql += "WHERE NOT EXISTS (SELECT 1 FROM Register WHERE email = ?)";
PreparedStatement ps = cn.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, mobile);
ps.setString(4, password);
ps.setString(5, conform_password);
ps.setString(6, email);
int i = ps.executeUpdate();
if (i == 0) {
System.out.println("Email already Exists Please Try with New Email");
}
else {
response.sendRedirect("index.html");
}
If the exists clause of the above insert fails, then nothing should be inserted, and the DML row count returned by executeUpdate() should be zero.
I am trying to implement a user registration using java and it always returns an error, my user login works fine. But why is this error?
I have implemented a register class which creates the connection and inserts the values. The input validation in done in the actionperformed class.
private boolean register(String username,String email,String password) {
try{
Class.forName("com.mysql.jdbc.Driver"); // MySQL database connection
Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/erp?" + "user=root&password=");
PreparedStatement sql = (PreparedStatement) conn.prepareStatement("Insert into user(username,email,password) values(? , ?, ?)");
sql.setString(1, username);
sql.setString(2, email);
sql.setString(3, password);
ResultSet rs = sql.executeQuery();
if(rs.next())
return true;
else
return false;
}
catch(Exception e){
e.printStackTrace();
return false;
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(jTextField1.getText().length()==0) // Checking for empty field
JOptionPane.showMessageDialog(null, "Insert Username");
else if(jTextField2.getText().length()==0) // Checking for empty field
JOptionPane.showMessageDialog(null, "Insert E-mail address");
else if(jPasswordField1.getText().length()==0) // Checking for empty field
JOptionPane.showMessageDialog(null, "Insert Password");
else if(jPasswordField2.getText().length()==0) // Checking for empty field
JOptionPane.showMessageDialog(null, "Re-enter Password");
else if(!jPasswordField1.getText().equals(jPasswordField2.getText())) // Checking for equal passwords
JOptionPane.showMessageDialog(null, "Password fields do not match");
else{
String user = jTextField1.getText(); // Collecting the input
String email = jTextField2.getText(); // Collecting the input
String pwd = jPasswordField1.getText(); // Collecting the input
//String pwd = pass; // converting from array to string
if(register(user,email,pwd))
JOptionPane.showMessageDialog(null, "Registered Successfully");
else
JOptionPane.showMessageDialog(null, "Error");
}
}
You have problem because you use PreparedStatement executeQuery method. But this method is good for querying database. And for updating database you have to use
PreparedStatement updateQuery method.
Short example:
String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "mkyong");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
// execute insert SQL stetement
preparedStatement .executeUpdate();
in this question your are mention what type of error you are getting
what ever it should be you just use debugger it will help you to resolve the bug
method executeQuery() is used to retrieve data from DB, like "Select" query/statements but if you want to run "update" ,"delete" or "insert" queries you have to use executeUpdate().use
ResultSet rs = sql.executeUpdate();
I Am currently working on a small project for myself which allows me to create new user to a database. Everything was going well until I noticed that one of my brackets on the code is displaying an error. Which is strange due to I checked I closed all of my brackets. If someone could see the missing bracket or help me fix the current ones it would be very useful.
JButton NewUserBtn = new JButton("Create New User");
NewUserBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Username = userText.getText();
String Password = passText.getText();
String Email = emailText.getText();
String cid = cidText.getText();
try {
Connection conn = DriverManager.getConnection( Host, Name, Pass );
PreparedStatement pst = conn.prepareStatement("SELECT `user_name`, `user_email` FROM `table_1` WHERE `user_name` = ? AND `user_email` = ?");
pst.setString(1, Username);
pst.setString(2, Password);
ResultSet Result = pst.executeQuery();
if (Result.next()) {
JOptionPane.showMessageDialog(null, "Error Account with Infomation already exists.");
}
else {
try {
PreparedStatement pst2 = conn.prepareStatement("INSERT INTO table_1 (user_name, user_pass, user_email, cid)"
+ " VALUES (?, ?, ?, ?)");
pst2.setString(1, Username); //Check Username does not exist!
pst2.setString(2, Password);
pst2.setString(3, Email); //Check Email is not already used!
pst2.setString(4, cid); //Need to add verification that CID is not in use!
pst2.execute();
}
catch (Exception e3) {
e3.printStackTrace();
}
}
}
});
The Bracket is the second to last one. Is says I should add finally but I do not understand why? Thanks for anyone who can solve this problem I'm having.
It's enough to only have one try statement. The code below should be working fine.
try {
Connection conn = DriverManager.getConnection( Host, Name, Pass );
PreparedStatement pst = conn.prepareStatement("SELECT `user_name`, `user_email` FROM `table_1` WHERE `user_name` = ? AND `user_email` = ?");
pst.setString(1, Username);
pst.setString(2, Password);
ResultSet Result = pst.executeQuery();
if (Result.next()) {
JOptionPane.showMessageDialog(null, "Error Account with Infomation already exists.");
} // if
else {
PreparedStatement pst2 = conn.prepareStatement("INSERT INTO table_1 (user_name, user_pass, user_email, cid)"
+ " VALUES (?, ?, ?, ?)");
pst2.setString(1, Username); //Check Username does not exist!
pst2.setString(2, Password);
pst2.setString(3, Email); //Check Email is not already used!
pst2.setString(4, cid); //Need to add verification that CID is not in use!
pst2.execute();
} // else
} // try
catch (Exception e3) {
e3.printStackTrace();
} // catch
You dont catch or finally your first try block.
You have added try-catch combination to inner try statement just above PreparedStatement, but outer try statement is missing catch or finally. See my comments below:
JButton NewUserBtn = new JButton("Create New User");
NewUserBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Username = userText.getText();
String Password = passText.getText();
String Email = emailText.getText();
String cid = cidText.getText();
try { //But it doesn't have either catch or finally
Connection conn = DriverManager.getConnection( Host, Name, Pass );
PreparedStatement pst = conn.prepareStatement("SELECT `user_name`, `user_email` FROM `table_1` WHERE `user_name` = ? AND `user_email` = ?");
pst.setString(1, Username);
pst.setString(2, Password);
ResultSet Result = pst.executeQuery();
if (Result.next()) {
JOptionPane.showMessageDialog(null, "Error Account with Infomation already exists.");
}
else {
try { //You have catch for this
PreparedStatement pst2 = conn.prepareStatement("INSERT INTO table_1 (user_name, user_pass, user_email, cid)"
+ " VALUES (?, ?, ?, ?)");
pst2.setString(1, Username); //Check Username does not exist!
pst2.setString(2, Password);
pst2.setString(3, Email); //Check Email is not already used!
pst2.setString(4, cid); //Need to add verification that CID is not in use!
pst2.execute();
}
catch (Exception e3) {
e3.printStackTrace();
}
}
}
});
I am trying to do insert to a table whose primary key is set to auto increment using a prepared statement.
The fields in the table are as follows;
id, username, password, email, firstname, last name
My code is such that
String sql = "INSERT INTO Users values (?,?,?,?,?, ?)";
RegistrationStatus status = null;
Connection conn = null;
PreparedStatement st = null;
try {
conn = source.getConnection();
st = conn.prepareStatement(sql);
st.setString(2, username);
st.setString(3, password);
st.setString(4, email);
st.setString(5, firstname);
st.setString(6, lastname);
st.executeUpdate();
Where i have read that we should no include the first item as the database will take care of it. This approach for me appears to be failing.
Would it be possible to get some help on how to solve this?
Change your statement to not include the id (or the exact name) column:
String sql = "INSERT INTO Users (username, password, email, firstname, lastname)"
+ " values (?,?,?,?,?)";
//...
st.setString(1, username);
st.setString(2, password);
st.setString(3, email);
st.setString(4, firstname);
st.setString(5, lastname);
//...