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();
}
}
}
});
Related
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>");
}
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");
}
Good day ,
While I am trying to update data after inserting new ones in the database,
This message is showing for me
can not issue executeupdate() for selects
I have checked tutorialspoint.com and codejava and the codes for both update and select are the same and the program is issuing the statement above
Here is my codes
String Sql="Select * from training where trainID=? ";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr","root","MZaa8891#");
ps= con.prepareStatement(Sql);
ps.setString(1, jTextField1.getText());
rs =ps.executeQuery();
while (rs.next()){
jTextField2.setText(rs.getString("traTitle"));
}
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
String Sql="Select * from training where traTitle =? ";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr","root","MZaa8891#");
ps= con.prepareStatement(Sql);
ps.setString(1, jTextField1.getText());
rs =ps.executeQuery();
while (rs.next()){
jTextField2.setText(rs.getString("trainID"));
}
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
String Sql= "UPDATE training SET traTitle ='"+ jTextField2.getText()+"', Type = "+(String) jComboBox1.getSelectedItem()+"', SDate = '"+sqlDate+"', Edate = '"+sqlDate2+"', location = '"+jTextField3.getText()+"',provider = '"+(String) jComboBox1.getSelectedItem()+"',related = '"+jTextArea1.getText()+"',benefits = '"+jTextArea2.getText()+"'important = '"+jTextArea3.getText()+"' WHERE trainID = "+jTextField1.getText()+"";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr","root","MZaa8891#");
Statement st = con.createStatement();
int i =ps.executeUpdate();
if (i>0)
{
JOptionPane.showMessageDialog(null, "Data is Saved");
}
else {
JOptionPane.showMessageDialog(null, "Data is not Saved");
}
}
catch (Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());
JOptionPane.showMessageDialog(null, e);
}
Any Solution ?
Statement st = con.createStatement();
int i = ps.executeUpdate();
The problem is here. You are creating a new, unused, Statement, and then trying to call executeUpdate() on the previously prepared statement, which was a SELECT.
This would have been avoided by correctly scoping the variables concerned as method-local. None of them should be instance or static members.
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 trying to check if a user entered Username and password matches one in my data base however what ever I try the result set still comes up null. the sql varible is set to the username and the pass is set to the password however when ever i enter the correct details it shows up with no results
public boolean Login(){
boolean valid = true;
try {
String stmt = "SELECT * From TBLUser where User = ? and Password = ? ;";
PreparedStatement pstmt = conn.prepareStatement(stmt);
pstmt.setString(1, sql); pstmt.setString(2, pass);
ResultSet rs = pstmt.executeQuery();
if(!rs.next()){
valid = false;
}
} catch (SQLException e) {
System.err.println("Error: "+e);
}
return valid;
}
Also, better practice:
public boolean Login(String asql, String apass){
boolean valid = true;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
String stmt = "SELECT * From TBLUser where User = ? and Password = ? ";
pstmt = conn.prepareStatement(stmt);
pstmt.setString(1, asql);
pstmt.setString(2, apass);
rs = pstmt.executeQuery();
valid = (!rs.next());
} catch (SQLException e) {
e.printStaceTrace();
} finally { // cleanup
try { rs.close(); } catch (Exception ex) {}
try { ps.close(); } catch (Exception ex) {}
}
return valid;
}
Use unit cap with " " to save your column-Table like
Create Table "TBLUser"{
"User" char...
"Password"...
}
similarly, your select query will change String
stmt = "SELECT * From \"TBLUser\" where \"User\" = ? and \"Password\" = ? "
This should work.
The problem with the application is not the code but the database as User one of the column names is a reserved word so this change fixed the problem thanks to #Grayson for all the help
public boolean Login(){
boolean valid = true;
try {
String stmt = "SELECT * From TBLUser where UserName = ? and Password = ? ;";
PreparedStatement pstmt = conn.prepareStatement(stmt);
pstmt.setString(1, sql); pstmt.setString(2, pass);
ResultSet rs = pstmt.executeQuery();
if(!rs.next()){
valid = false;
}
} catch (SQLException e) {
System.err.println("Error: "+e);
}
return valid;
}