Skip to main content

Change Password functionality using JDBC

Change Password functionality using JDBC

we already created table Password_info in mysql

password_table

JDBC program to Implement change password functionality

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package jdbc;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
 
public class Passwordupdate
{
 
	public static void main(String[] args)
	{
 
	 Connection con=null;
	 PreparedStatement pstmt=null;
 
	 String username="bhavesh";
	 String old_password="12345";
	 String new_password="4321";
 
  try{ 
 
	     /*
	      * 1.load the driver
	      */
		Class.forName("com.mysql.jdbc.Driver").newInstance();
 
		/*
		 * 2.get the db connection via driver
		 */
		String dburl="jdbc:mysql://localhost:3306/test?user=root&password=root";
	    con=DriverManager.getConnection(dburl);
 
	    /*
	     * 3.issue sql query via connection
	     */
		String query="update password_info "
	                 + " set current_password=? "
				     + " where user=? and current_password=?";
 
 
		       pstmt=con.prepareCall(query);
 
		       pstmt.setString(1,new_password);
		       pstmt.setString(2,username);
		       pstmt.setString(3,old_password);
 
 
		       int count=pstmt.executeUpdate();
 
		      if(count>0)
		      {
		    	  System.out.println("password successfully changed");
		      }
		      else
		      {
		       System.out.println("unable to change password, provide right credential");
		      }
         }
 
        catch(Exception e)
         {
 
	       e.printStackTrace();
         }
 
           finally
           {
        	   try {
				if(con!=null)
				   {
					   con.close();
				   }
				   if(pstmt!=null)
				   {
 
					  pstmt.close();  
				   }
			} 
 
        	   catch (SQLException e) 
        	   {
				// TODO Auto-generated catch block
				e.printStackTrace();
	           }
              }  
 
 
	}
  }
 
output:
password successfully changed
After changing password

updated-password