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();
Related
I was trying to make a registration page that takes two infos
The registration is like this: you enter 3 information and you click the "next" button to go to another page and enter the personal data then submit
but the problem is I can't get the account info to save it into the database
I am using struts2
the first page just check if the username or email has duplicate, if it has then the action class will return "failed" then refresh the page. If it doesn't have dups then it will go to the second page.
is there something like httpsession?
here's my code
checkEmail vMail = new checkEmail();
checkUser vUser = new checkUser();
int mailCount = vMail.dba(email);
int userCount = vUser.dba(username);
if(mailCount == 0){
if(userCount == 0){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/march4","root",sc.pass);
String add = ("INSERT INTO accountdata VALUES(?, ?, ?, ?)");
PreparedStatement st = con.prepareStatement(add);
st.setInt(1, 0);
st.setString(2, getUsername());
st.setString(3, getPassword());
st.setString(4, getEmail());
st.executeUpdate();
st.close();
con.close();
return "success";
}catch(ClassNotFoundException e){
return "failed";
} catch (SQLException e) {
return "failed";
}
}else{return "failed";}
}else{return "failed";}
And here's the code for my second action class
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/march4","root",sc.pass);
String user = ("SELECT username FROM accountdata WHERE password ="+getCpassword());
Statement state = con.createStatement();
ResultSet rs = state.executeQuery(user);
username = rs.getString(user);
String mail = ("SELECT email FROM accountdata WHERE password ="+getCpassword());
ResultSet rs2 = state.executeQuery(mail);
email = rs2.getString(mail);
I have private String username and password
and did I use the correct syntax for mysql?
I have two tables and I use the password and confirm password for the key
code in update button
String password = new String(oldPass.getPassword());
String newPassword = new String(newPass.getPassword());
String realpass = zz.getText();
String us = z.getText();
if(password.equals(realpass))
{
System.out.println("ok");
String query = "UPDATE user SET password = '"+newPassword+"' WHERE username = '"+us+"'";
try{
Statement st = (Statement) con.prepareStatement(query);
int i = st.executeUpdate(query);
if(i!=0){
JOptionPane.showMessageDialog(null, "Your password is successfully changed!");
}
else{
JOptionPane.showMessageDialog(null, "Ooopps! I guess you should call your programmer. ^^");
}
}catch(Exception e){
System.out.println(e);
}
}
code in log in
Methods m = new Methods();
String pass = new String (password.getPassword());
String user = username.getText();
if(m.logInUser(user, pass)==true){
form2 f = new form2();
f.setUser(user);
f.setPass(pass);
f.setVisible(true);
this.dispose();
}....and so on....
code for method log in user
public boolean logInUser(String user, String pass){ //true = nakarecord na sa database login form
try{
String query = "Select * from user where username = ? && password = aes_encrypt('"+pass+"', 'nicanor')";
PreparedStatement pst = (PreparedStatement) con.prepareStatement(query);
pst.setString(1,user);
ResultSet rs = pst.executeQuery();
if(rs.next()){
return true;
}
else{
return false;
}
}
catch(Exception e){
System.out.println(e);
return false;
}
}//logInUser
it says successfully connected in sql and the database is updated but i cant see the next form that should pop up after i entered the updated password
There are few problems with your code:
(1) In your update() logic, you are using the mix of PreparedStatement and Statement together, rather use always use PreparedStatement to bind the input parameters, otherwise they (statements/queries) are prone to SQL injection attacks.
You can refer the below code with inline comments to bind the input parameters with PreparedStatement:
//Write the SQL query with ? to bind the parameters in PreparedStatement
String query = "UPDATE user SET password = ? WHERE username = ?";
PreparedStatement pstmt = null;
try{
//create the PreparedStatement object
pstmt = con.prepareStatement(query);
//bind the input parameters using setString()
pstmt.setString(1, newPassword);
pstmt.setString(2, us);
//execute the prepare statement now
int i = pstmt.executeUpdate(query);
if(i!=0){
JOptionPane.showMessageDialog(null, "Your password
is successfully changed!");
}
else{
JOptionPane.showMessageDialog(null,
"Ooopps! I guess you should call your programmer. ^^");
}
} catch(Exception e){
System.out.println(e);
} finally {
if(pstmt != null)
pstmt.close();
if(con != null)
con.close();
}
Also, remember that database resources are costly and you need to close the resources in the finally block as shown above, otherwise you will end up with resource leaks.
(2) In your logInUser() logic, you are using && which is incorrect, rather in sql you need to use AND operator as shown below:
String query = "Select * from user where username = ?
AND password = aes_encrypt('"+pass+"', 'nicanor')";
I have a registration page where information for a customer can be entered into 4 text fields, i.e. Customer name, customer address, customer email and customer contact number.
I was wondering how to get the data from the text fields and into the Derby Database in netbeans using Java.
Well, you need to get the text from the fields first, so as follows:
//Replace the textfield names with your textfield variable names
String customerName = txtFieldCustomerName.getText();
String customerAddress = txtFieldCustomerAddress.getText();
String customerEmail = txtFieldCustomerEmail.getText();
String customerContactNumber = txtFieldCustomerContactNumber.getText();
Now that we have all the data, we can perform a database insert
Connection con = null;
PreparedStatement pstmt = null;
try {
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
//Get a connection
con = DriverManager.getConnection("jdbc:derby://localhost:1527/myDB;create=true;user=me;password=mine");//Replace this with your information to your database
//now we have a connection, we can perform the insert
pstmt = con.prepareStatement("insert into TABLE_NAME_HERE (customerName, customerAddress, customerEmail, customerContactNumber) VALUES (?, ?, ?, ?)");
pstmt.prepareString(1, customerName);
pstmt.prepareString(2, customerAddress);
pstmt.prepareString(3, customerEmail);
pstmt.prepareString(4, customerContactNumber);
pstmt.executeUpdate(); //execute the insert
} catch(SQLException sqle) {
sqle.printStackTrace();
}
finally { //close the connection after everything is done.
try {
con.close();
pstmt.close();
} catch(SQLException sqle) {
sqle.printStackTrace();
}
}
The update does not apply when i try to change the variable while running the program. It does not have any errors.
It says the update is recorded successfully but it does not apply to Mysql.
Please help!
StaffDA
public void actionPerformedUpdate() {
if (StaffDA.updateCustomer(customer)) {
txtfName.setEditable(false);
txtlName.setEditable(false);
txtGender.setEditable(false);
txtEmail.setEditable(false);
txtDateOfBirth.setEditable(false);
txtUserId.setEditable(false);
txtPassword.setEditable(false);
txtContactNumber.setEditable(false);
txtAddress.setEditable(false);
JOptionPane.showMessageDialog(myFrame,
"Record updated successfully", "Alert",
JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(myFrame,
"Database Error. Record not updated.", "Alert",
JOptionPane.ERROR_MESSAGE);
}
}
StaffUpdatePanel
public static boolean updateCustomer(Customer customer) {
//declare local variables
boolean success = false;
DBController db = new DBController();
String dbQuery;
PreparedStatement pstmt;
//step 1 - establish connection to database
db.getConnection();
//step 2 - declare the SQL statement
dbQuery = "UPDATE customer SET fName = ?, lName = ?, gender = ?, email = ?, dateOfBirth = ?, userId = ?, password = ? ,contactNumber = ?, address = ? WHERE id = ?";
pstmt = db.getPreparedStatement(dbQuery);
//step 3 - to update record using executeUpdate method
try {
pstmt.setString(1, customer.getfName());
pstmt.setString(2, customer.getlName());
pstmt.setString(3, customer.getGender());
pstmt.setString(4, customer.getEmail());
pstmt.setString(5, customer.getDateOfBirth());
pstmt.setString(6, customer.getUserId());
pstmt.setString(7, customer.getPassword());
pstmt.setString(8, customer.getContactNumber());
pstmt.setString(9, customer.getAddress());
pstmt.setInt(10, customer.getId());
if (pstmt.executeUpdate() == 1)
success = true;
pstmt.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(success);
//step 4 - close connection
db.terminate();
return success;
}
It could be a problem with the database user's access rights to the database. If you can do a select statement on the database, you could have set the DB user to only have read access.
Also you could try to print out the update statement and run in manually on the database with the same user, to see if the database system itself can run the update correctly, in this case you have narrowed down the problem to the code and not access rights.
I'm tring read the data from reg form and insert it to a db, this part should add the item but it doesn't work. Do you have a recommendation ?
if ("/RegForm".equals(url)) {
request.getRequestDispatcher("/index.jsp").forward(request, response);
return;
} else if ("/Signup".equals(url)) {
//dddddddd
try {
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/deneme", "root", "");
Statement stmt = conn.createStatement();
// Execute SQL query
String sql1 = "INSERT INTO students (name, id, `gpa`) VALUES ("+ request.getParameter("st_name") +","+ request.getParameter("st_id") +","+ request.getParameter("st_gpa") +")";
stmt.executeUpdate(sql1);
} catch (Exception se) {
//Handle errors for JDBC
}
request.getRequestDispatcher("/register_action.jsp").forward(request, response);
return;
}
ps: i'm really not familiar using java in web apps, just trying to learn.
You should use preparedStatement to avoid sql injection, your code should be:
if ("/RegForm".equals(url)) {
request.getRequestDispatcher("/index.jsp").forward(request, response);
return;
} else if ("/Signup".equals(url)) {
//dddddddd
try {
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/deneme", "root", "");
PreparedStatement preparedStatement = null;
// Execute SQL query
String insert= "INSERT INTO students (name, id, `gpa`) VALUES (?,?,?)";
conn.setAutoCommit(false);
preparedStatement = con.prepareStatement(insert);
//Assume all paramaters as String
preparedStatement.setString(1, request.getParameter("st_name"));
preparedStatement.setString(2, request.getParameter("st_id"));
preparedStatement.setString(3, request.getParameter("st_gpa"));
preparedStatement.executeUpdate();
conn.commit();
} catch (Exception se) {
//Handle errors for JDBC
}
request.getRequestDispatcher("/register_action.jsp").forward(request, response);
return;
}
You can check here for more detailed example
Any specific error you are getting..?
Or do one thing just print the count like this:
int count= stmt.executeUpdate(sql1);
Check the value of count. put some S.O.P inside else condition and cross check whether it is going to that section or not.