I'm building this component where I can change the password that is stored in my MySQL database using Java Eclipse. I have this typical system where you have to enter your old password and new password and have that old password checked to match the one in the system.
public class ChangePassword implements ActionListener {
public void actionPerformed(ActionEvent event) {
JPasswordField oldPswrd = new JPasswordField(50);
JPasswordField newPswrd = new JPasswordField(50);
JLabel j = new JLabel("Type in old password: ");
JLabel j2 = new JLabel("Type in new password: ");
j.setFont(new Font("Times New Roman", Font.PLAIN, 15));
j2.setFont(new Font("Times New Roman", Font.PLAIN, 15));
Object[] message = {
j, oldPswrd,
j2, newPswrd,
};
int result = JOptionPane.showConfirmDialog(null, message,
"CHANGE PASSWORD", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
char[] oldp = oldPswrd.getPassword();
String oldP = String.valueOf(oldp);
char[] p = newPswrd.getPassword();
String newP = String.valueOf(p);
System.out.println("New name: " + newP);
//// PROBLEM SEEMS TO START HERE ///////////////////////////////////////////
try {
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println("connection success!!");
String sql = "SELECT * FROM user_info WHERE user_id = ? && user_password = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, user_id);
statement.setString(2, password);
ResultSet rs = statement.executeQuery();
if (rs.next()){
String oldPassword = rs.getString("user_password");
if (oldP.equals(oldPassword)) {
String sql1 = "UPDATE user_info SET user_password = ? WHERE user_id = ?";
PreparedStatement statement1 = connection.prepareStatement(sql1);
statement1.setString(1, newP);
statement1.setString(2, user_id);
int rows2 = statement1.executeUpdate();
if (rows2 > 0) {
System.out.println("UPDATE PASSWORD!");
}
}
} else {
JLabel l = new JLabel("Old password does not match");
l.setFont(new Font("Times New Roman", Font.PLAIN, 15));
l.setHorizontalAlignment(SwingConstants.CENTER);
JOptionPane.showMessageDialog(null, l, "ERROR", JOptionPane.PLAIN_MESSAGE);
}
} catch (SQLException e) {
System.out.println("& i oop");
e.printStackTrace();
}
///////// PROBLEM SEEMS TO END HERE ///////////////////////////////////////////
frame.setVisible(false);
new UserMain(user_id, name, newP);
}
}
}
I have this table with a row of data already set in as a test. However, whenever I try to change the password - typing in the correct old password and typing in another new one - it always shows
old password does not match
There's no syntax or connection errors so I figured the problem is a logic error or something I couldn't catch. Also, the java portions work fine, I've checked those already. The problem seems to be between the try and catch parts of my code.
password is your database password, not one of the user passwords. Change
statement.setString(2, password);
to
statement.setString(2, oldP);
Where are you taking this "username" and "password" from?
Also you are passing the same "password" variable to find the user that is using for the DB connection. I think it should be change to "oldP ".
Related
I have 3 questions regarding my code below used for user registration.
1) How can I prevent users from registering themselves providing empty value in the username and password area?
2) I wonder if it's a good practice to both dispose & run the form again in case user credentials already exist in database. Is there any other way to go back to the main screen?
3) My programs runs correctly but there is a warning message in a line like "The method getText() from the type JPasswordField is deprecated". What does that mean exactly?
Code:
public void actionPerformed(ActionEvent arg0) {
try
{
String userID = userIDinput.getText();
String pass = passwordField.getText();
String myDriver = "com.mysql.jdbc.Driver"; //jdbc driver loaded
String myUrl = "jdbc:mysql://localhost:3306/masterdata_db?autoReconnect=true&useSSL=false";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
Statement st = conn.createStatement();
ResultSet resultSet;
String check = "SELECT Username FROM userregistration WHERE Username = '"+userID+"' ";
resultSet = st.executeQuery(check);
if(!resultSet.next()){
String sql = "INSERT INTO userregistration"
+ "(Username, Password) VALUES"
+ "(?,?)";
PreparedStatement pSt=conn.prepareStatement(sql);
pSt.setString(1, userID);
pSt.setString(2, pass);
pSt.executeUpdate();
conn.close();
}
else {
JOptionPane.showMessageDialog(frame, "USER ALREADY EXISTS. TRY ANOTHER ONE!", "Inane error",JOptionPane.ERROR_MESSAGE);
dispose();
new Login().setVisible(true);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
1)
if(userID.trim().isEmpty())//trim removes whitespaces
{
throw new SomeKindOfException();
//or just ...
return;
}
See this question.
2) Just remove the dispose and new Login(). JOptionPane will automatically "return to your main screen".
3) You should use password-fields like this:
JPasswordField passwordField = new JPasswordField();
char[] chars = passwordField.getPassword();
String pwd = new String(chars);
for (int i=0; i<chars.length; i++) chars[i] = ’x’; //overwrite password when done for more security
See How to Use Password Fields for more information.
The JPasswordField uses char[] instead of String, because Strings are immutable.
For more information see this question.
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'm writing a program where the user has to sign in. I've reviewed my code again and again but I keep getting "null" as the error. This is not only the case for the sign in part of the program, but also for the part where the user can create an account. Basically, wherever I've implemented JDBC, a "null" error pops up. How do I fix this?
String user_name_check = user_name.getText().trim();
char[] pass = password_enter.getPassword();
String password_check = Arrays.toString(pass);
String query = "SELECT * FROM USER_INFO WHERE USERNAME = '" + user_name_check + "';";
try{
rs = st.executeQuery(query);
if(rs.next()){
//changing the panel (start)
if(password_check.equals(rs.getString("PASS"))){
MAIN.removeAll();
MAIN.add(news_feed);
MAIN.repaint();
MAIN.revalidate();
//changing the panel (end)
//giving values to class level field variables (start)
username = user_name_check;
firstname = rs.getString("FIRST_NAME");
lastname = rs.getString("LAST_NAME");
dob = rs.getString("DOB");
gender = rs.getString("GENDER");
bio = rs.getString("BIO");
home_user_name.setText(username);
set_dp(home_user_dp, username);
}
}
else sign_in_message.setVisible(true);
}
catch(Exception e){
System.out.println(e.getMessage() + " #jButton2ActionPerformed SIGN IN");
}
The error : null #jButton2ActionPerformed SIGN IN
EDIT
Here's the JDBC connection method :
public void JDBC_Connect(){
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/socialnetwork", "root", "mukundrox");
st = con.createStatement();
}
catch(Exception e){
System.out.println(e.getMessage() + " #JDBC_connect");
}
}
I designed a swing interface with MySQL table. I put two comboboxes in a manner when the 1st combobox value is selected (Brand Name), the second combobox values (available items under thise selected brand) will be loaded via a mysql query. My code is...
try{
String url = "jdbc:mysql://localhost:3306/databasename";
String login = "root"; String password = ""; Connection con = DriverManager.getConnection(url, login, password);
try{
comboBox1 = new JComboBox(); comboBox1.setEditable(false);
comboBox1.addItem("- - -");
Statement stmt1=null;
String query1 = "SELECT brand FROM brands";
stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery(query1);
while(rs1.next()) {comboBox1.addItem(rs1.getString(1));}
comboBox2 = new JComboBox(); comboBox2.setEditable(false);
comboBox1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event){
String comboBox1Selected=comboBox1.getSelectedItem().toString();
try{
Statement stmt2=null;
String query2 = "SELECT item FROM "+comboBox1Selected+"";
stmt2 = con.createStatement();
ResultSet rs2 = stmt2.executeQuery(query2);
while(rs2.next()) {comboBox2.addItem(rs2.getString(1));}
}
catch (SQLException ex1) {JOptionPane.showMessageDialog(null,"Failed to Item-List..!"); ex1.printStackTrace(); return;}
}
});
}
catch (SQLException ex2) {JOptionPane.showMessageDialog(null,"Failed to Brand-List..!"); ex2.printStackTrace(); return;}
}
catch (SQLException ex3) {ex3.printStackTrace(); JOptionPane.showMessageDialog(null,"Unable to Connect..!"); return;}
The problem is, eventhough the comboboxes are functioning correctly, if I select another choice from 1st combobox, the second combobox doesn't avoid the "older values" (they appears with the newer values).
What might be the reason..? Anyone could explain..?
Thanks in advance.
Call comboBox2.removeAllItems() before adding the new items here while(rs2.next()) {comboBox2.addItem(rs2.getString(1));}
I have written a code to delete a record in a MySQL database from my Java Program. It compiles and runs it successfully, but the record is still in the datbase. Any suggestions?
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
Object[] options = {"Yes", "No"};
Component form = null;
int n = JOptionPane.showOptionDialog(form, "Do you like to delete the record for Student ID: " +
textField_16.getText() + " ?", "Exit Confirmation", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options);
if(n == JOptionPane.YES_OPTION) {
String mock = textField_16.getText();
String sql = "DELETE FROM mockexam WHERE MockID =?";
PreparedStatement prest = con.prepareStatement(sql);
prest.setString(1, mock);
int val = prest.executeUpdate();
JOptionPane.showMessageDialog(frmDeleteMock, "The record has been deleted successfully.");
}
}
catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(frmDeleteMock, "Record couldn't be deleted. Please try again.");
}
}
});
btnDelete.setBounds(45, 235, 89, 23);
panel_1.add(btnDelete);
You don't indicate what kind of DB you are running against (innoDB or MyISAM, etc) but if you are running against InnoDB, you need to have a commit() statement to commit the transaction after your executeUpdate(). Chances are you have something in your log that indicates that your transaction has been rolled back.
try {
Object[] options = {"Yes", "No"};
Component form = null;
int n = JOptionPane.showOptionDialog(form,
"Do you like to delete the record for Student ID: " + textField_16.getText() + " ?",
"Exit Confirmation", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options);
if(n == JOptionPane.YES_OPTION) {
String sql = "DELETE FROM mockexam WHERE MockID =?";
PreparedStatement prest = con.prepareStatement(sql);
prest.setString(1, "MockID");
prest.executeUpdate();
con.commit();
JOptionPane.showMessageDialog(frmDeleteMock, "The record has been deleted successfully.");
}
}
catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(frmDeleteMock, "Record couldn't be deleted. Please try again.");
}
You're also missing connection an PreparedStatement close() calls in a finally{} block to ensure that you don't have any leaks in your code.
prest.setString(1, "MockID");
You are looking for a MockID equal to MockID I assume you want to delete a entry with a certain ID use:
String mockID = "2"; //Set this however you want to set it.
prest.setString(1, mockID);
int val = prest.executeUpdate();
//Check val for what happened.
If no records match your criterion then the SQL will be deemed to have worked. Hence I'd be suspicious of the parameter. What's the type of the column in the database? Could it be a fixed length value and so not match "MockID"?