Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Can you Kindly Help me out on my adding/editing database connections

  1. #1
    Junior Member
    Join Date
    Dec 2012
    Posts
    12
    My Mood
    Confused
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Can you Kindly Help me out on my adding/editing database connections

    import java.awt.Dimension;
    import java.sql.*;
    import javax.swing.*;
    import java.awt.event.*;
     
    public class AccountsManagement extends javax.swing.JFrame {
     
    	private String currentUsername;
    	private Login parent;
    	private DatabaseConnect data;
     
    	public AccountsManagement(String username, Login d, DatabaseConnect dc) {
    		parent = d;
    		currentUsername = username;
    		this.data = dc;
    	}
     
        private AccountsManagement() {
            start();
            initComponents();
     
        }
     
    	public void start() {
    		try {
    			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
    				if ("Windows".equals(info.getName())) {
    					javax.swing.UIManager.setLookAndFeel(info.getClassName());
    					break;
    				}
    			}
    		} catch (Exception ex) {
    			System.out.println(ex.getMessage());
    		}
    		initComponents();
    		this.setLocationRelativeTo(null);
    		this.setVisible(true);
    	}
     
     
     
    	// GUI 
     
        @SuppressWarnings("unchecked")
        private void initComponents() {
     
    jScrollPane1 = new JScrollPane();
            jTextArea1 = new JTextArea();
            jButton5 = new JButton();
            jLabel1 = new JLabel();
            jLabel2 = new JLabel();
            jLabel3 = new JLabel();
            jLabel4 = new JLabel();
    jchbUsername = new JCheckBox();
            jbtnAdd = new JButton();
            jchbPassword = new JCheckBox();
            jbtnShow = new JButton();
            jbtnDelete = new JButton();
            jSeparator1 = new JSeparator();
            jSeparator2 = new JSeparator();
            jSeparator3 = new JSeparator();
            jbtnLogoff = new JButton();
            jbtnEdit = new JButton();
            jSeparator4 = new JSeparator();
            jLabel5 = new JLabel();
     
            jTextArea1.setColumns(20);
            jTextArea1.setRows(5);
            jScrollPane1.setViewportView(jTextArea1);
     
            jButton5.setText("jButton5");
     
            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
            setTitle("Account Management");
            setResizable(false);
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosed(java.awt.event.WindowEvent evt) {
                    amClose(evt);
                }
            });
     
            jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
            jLabel1.setText("Add a new user account");
     
            jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
            jLabel2.setText("Edit your account details");
     
            jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
            jLabel3.setText("Show all user accounts");
     
            jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
            jLabel4.setText("Delete an account");
     
            jchbUsername.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
            jchbUsername.setText("Username");
     
            jbtnAdd.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
            jbtnAdd.setText("Add");
            jbtnAdd.setToolTipText("");
            jbtnAdd.addActionListener(new java.awt.event.ActionListener() {
     
     
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jbtnAddActionPerformed(evt);
                }
            });
     
            jchbPassword.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
            jchbPassword.setText("Password");
     
            jbtnShow.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
            jbtnShow.setText("Show");
            jbtnShow.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jbtnShowActionPerformed(evt);
                }
            });
     
            jbtnDelete.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
            jbtnDelete.setText("Delete");
            jbtnDelete.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jbtnDeleteActionPerformed(evt);
                }
            });
     
            jbtnLogoff.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
            jbtnLogoff.setText("Logoff");
            jbtnLogoff.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jbtnLogoffActionPerformed(evt);
                }
            });
     
            jbtnEdit.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
            jbtnEdit.setText("Edit");
            jbtnEdit.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jbtnEditActionPerformed(evt);
                }
            });
     
            jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
            jLabel5.setText("Logoff from the system");
     
            GroupLayout layout = new GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jSeparator3)
                        .addComponent(jSeparator4)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(jLabel2)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
                            .addComponent(jchbPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel1)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jbtnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(jSeparator1)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 55, Short.MAX_VALUE)
                                .addComponent(jbtnShow, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.LEADING))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel4)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jbtnDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel5)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jbtnLogoff, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addGap(0, 0, Short.MAX_VALUE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jchbUsername, javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jbtnEdit, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jbtnAdd))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 0, 0)
                    .addComponent(jchbUsername)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jchbPassword)
                        .addComponent(jLabel2))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jbtnEdit)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(jbtnShow))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel4)
                        .addComponent(jbtnDelete))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel5)
                        .addComponent(jbtnLogoff))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
     
            pack();
        }// </editor-fold>
     
    /**************************************
     *      END of GUI INITIALIZATION     *
     **************************************/     
     
     
     
     
     
    private void jbtnAddActionPerformed (ActionEvent evt) {                                        
     
     
    		String title = "Add new account", 
    user = "", pass = "";
    		int choice = JOptionPane.CANCEL_OPTION;
    		do {
    user = JOptionPane.showInputDialog(this, "Enter username", user, JOptionPane.INFORMATION_MESSAGE);
    			if (user == null) {
    				return;
    			}
    		} while (user.isEmpty());
     
    		do {
    pass = JOptionPane.showInputDialog(this, "Enter password", pass, JOptionPane.INFORMATION_MESSAGE);
    			if (pass == null) {
    				return;
    			}
    		} while (pass.isEmpty());
    choice = JOptionPane.showConfirmDialog(this, "Add user with username "
    				+ user + "?", title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
     
    		if (choice == JOptionPane.YES_OPTION) {
    			data.addUser(user, pass);
     
     
    			JOptionPane.showMessageDialog(this, "User added!", title, JOptionPane.INFORMATION_MESSAGE);
    		}
    	}
     
    	private void EditUser(boolean user, boolean pass) {
    		String title = "Edit your account";
    		int choice;
    		if (user) {
    			String username;
    			do {
    				username = JOptionPane.showInputDialog(this, "Enter new username", title, JOptionPane.PLAIN_MESSAGE);
    				if (username == null) {
    					return;
    				}
    			} while (username.isEmpty());
     
    			choice = JOptionPane.showConfirmDialog(this, "Change your username?", title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
    			if (choice == JOptionPane.OK_OPTION) {
    				int x = data.editUsername(username, currentUsername);
    				if (x > 0) {
    					JOptionPane.showMessageDialog(this, "Username updated", title, JOptionPane.INFORMATION_MESSAGE);
    					currentUsername = username;
    				} else {
    					System.out.println("record not updated");
    				}
    			} // end if choice block
    		} // end edit username block
    		if (pass) {
    			String password;
    			do {
    				password = JOptionPane.showInputDialog(this, "Enter new password", title, JOptionPane.PLAIN_MESSAGE);
    				if (password == null) {
    					return;
    				}
    			} while (password.isEmpty());
     
    			choice = JOptionPane.showConfirmDialog(this, "Change your password?", title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
     
    			if (choice == JOptionPane.OK_OPTION) {
    				System.out.println("current username when changing password is "
    						+ currentUsername);
    				int x = data.editPassword(password, currentUsername);
    				if (x > 0) {
    					JOptionPane.showMessageDialog(this, "Password was successfully changed", title, JOptionPane.INFORMATION_MESSAGE);
    				} else {
    					System.out.println("password was not changed");
    				}
    			}// end if okoption block
    		}
    		if (!user && !pass) {
    			JOptionPane.showMessageDialog(this, "Nothing was selected for editing", "Error", JOptionPane.ERROR_MESSAGE);
    		}
    	} // end edit user method
     
    	private void amClose(WindowEvent evt) {
    		this.jbtnLogoffActionPerformed(null);
    	}
     
    	private void jbtnEditActionPerformed(ActionEvent evt) {
    		EditUser(jchbUsername.isSelected(), jchbPassword.isSelected());
    	}
     
    	private void jbtnShowActionPerformed(ActionEvent evt) {
    		try {
    			String UserPass[][] = data.showAccounts();
    			String header[] = { "username", "password" };
    			JTable showData = new JTable(UserPass, header);
    			showData.setEnabled(false);
    			JScrollPane jspData = new JScrollPane(showData);
    			jspData.setPreferredSize(new Dimension(100, 100));
    			JOptionPane.showMessageDialog(this, jspData, "Show all accounts", JOptionPane.PLAIN_MESSAGE);
    		} catch (Exception e) {
    			System.out.println(e.getMessage());
    		}
    	}
     
    	private void jbtnLogoffActionPerformed(ActionEvent evt) {
    		int choice = JOptionPane.showConfirmDialog(this, "Logoff the system?", "Logoff", JOptionPane.YES_NO_OPTION);
    		if (choice == JOptionPane.YES_OPTION) {
    			this.setVisible(false);
    			parent.showLogin();
    			data.logoff();
    		}
    	}
     
    	private void jbtnDeleteActionPerformed(ActionEvent evt) {
    		this.jbtnShowActionPerformed(evt);
    		String user = "", title = "Delete a user account";
     
    		do {
    			user = JOptionPane.showInputDialog(this, "Enter username of account to delete", title, JOptionPane.PLAIN_MESSAGE);
    			if (user == null) {
    				return;
    			}
    			if (user.equals(currentUsername)) {
    				this.jbtnLogoffActionPerformed(evt);
    			}
    		} while (user.isEmpty());
     
    		int choice = JOptionPane.showConfirmDialog(this, "Are you sure you want to delete user "
    				+ user + "?", title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
    		if (choice == JOptionPane.OK_OPTION) {
    			int x = data.deleteAccount(user);
    			if (x > 0) {
    				JOptionPane.showMessageDialog(this, "Account with username " + user + " has been deleted", title, JOptionPane.INFORMATION_MESSAGE);
    			}
    		}
    	}
     
    	// Variables declaration
    	private javax.swing.JButton jButton5;
    	private JLabel jLabel1,  jLabel2, jLabel3, jLabel4, jLabel5;
    	private JScrollPane jScrollPane1;
    	private JSeparator jSeparator1, jSeparator2, jSeparator3, jSeparator4;
    	private JTextArea jTextArea1;
    	private JButton jbtnAdd, jbtnDelete, jbtnEdit, jbtnLogoff, jbtnShow;
    	private JCheckBox jchbPassword, jchbUsername;
    	// End of variables declaration
     
            public static void main(String[] args) {
            AccountsManagement p = new AccountsManagement();
            p.setVisible(true);
     
     
        }
    }
     
    //****************DatabaseConnect*****************//
     
     
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import javax.swing.*;
    import java.sql.Statement;
     
    public class DatabaseConnect {
    	private Connection con;
    	private ResultSet rs;
    	private PreparedStatement LoginSt, addUserSt, editUsernameSt, editPassSt, deleteUserSt;
     
    	public DatabaseConnect() {
    		connect();
    	}
     
            private void connect() {
    	System.out.println("inside the connect method of database connect");
    	try {
    			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                            con = DriverManager.getConnection("jdbc:odbc:db1");
     
    	LoginSt = con.prepareStatement("select user, pass from Table1 where user = ? and pass = ?");
    	addUserSt = con.prepareStatement("insert into Table1 (user,pass) values(?,?)");
    	editUsernameSt = con.prepareStatement("update Table1 set user = ? where user = ?");
    	editPassSt = con.prepareStatement("update Table1 set pass = ? where user = ?");
    	deleteUserSt = con.prepareStatement("delete from Table1 where user = ?");
     
    } catch (Exception e) {
    	System.out.println(e.getMessage());
    	}
    }
     
    public int login(String name, String pass) {
                int count = 0;
    	try {
    		LoginSt.setString(1, name);
    		LoginSt.setString(2, pass);
    		rs = LoginSt.executeQuery();
    		count = 0;
    		while (rs.next())
    			count++;
    	} catch (Exception e) {
    		System.out.print(e.getMessage());
    	} finally {
    	return count; }
     
    }
    public void addUser(String user, String pass) {
     
        try {
    		addUserSt.setString(1, user);
    		addUserSt.setString(2, pass);
     
    		int x = addUserSt.executeUpdate();
    	} 
                    catch (Exception ex) {
    		System.out.println("add user");
                   // JOptionPane.showMessageDialog(null,"age and phone must be in number format or too long");
    	}
     
    }
     
    public int editUsername(String username, String currentUsername) {
    	int x = 0,count = 0;
    	try {
     
    		editUsernameSt.setString(1, username);
    		editUsernameSt.setString(2, currentUsername);
    		x = editUsernameSt.executeUpdate();
                    count = 0;
    		while (rs.next())
    			count++;
     
    	} catch (Exception e) {
    		System.out.println("edit username");
    			System.out.println(e.getMessage());
    	} finally {
    		return x;
    	}
    }
     
    public int editPassword(String password, String currentUsername) {
    	int x = 0;
    	try {
    		editPassSt.setString(1, password);
    		editPassSt.setString(2, currentUsername);
    		x = editPassSt.executeUpdate();
    	} catch (Exception e) {
    			System.out.println(e.getMessage());
    	} finally {
    		return x;
    	}
    }
    public String[][] showAccounts() {
    	rs = null;
    	int x = 0;
    	String data[][] = null;
    	try {
    		Statement st = con.createStatement();
    		rs = st.executeQuery("select count(*) from Table1");
    		rs.next();
    		x = rs.getInt(1);
    	       rs = st.executeQuery("select user, pass from Table1");
    		data = new String[x][2];
    		int i = 0;
    		while (rs.next()) {
    			data[i][0] = rs.getString(1);
    			data[i][1] = rs.getString(2);
    			i++;
    		}
    	} catch (Exception e) {
    		System.out.println(e.getMessage());
    	} finally {
    	return data;  } }
     
     
     
     
    public int deleteAccount(String user) {
    	int x = 0;
    	try {
    			this.deleteUserSt.setString(1, user);
                            x = deleteUserSt.executeUpdate();
    	} catch (Exception e) {
    			System.out.println(e.getMessage());
    	} finally {
    		return x;
    	}
    }
     
     
     
    public void close() {
    	try {
    		this.addUserSt.close();
    		this.deleteUserSt.close();
    		this.editPassSt.close();
    		this.editUsernameSt.close();
    		this.LoginSt.close();
    		this.rs.close();
    		this.con.close();
    	} catch (Exception e) {
    		System.out.println(e.getMessage());
    	}
    }
     
     
    }


  2. #2
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 139 Times in 134 Posts

    Default Re: Can you Kindly Help me out on my adding/editing database connections

    Please don't post the same question multiple times in the forum.

    Locked.

Similar Threads

  1. [SOLVED] database connection problem adding,deleting,updating,selecting :(
    By jabaman in forum What's Wrong With My Code?
    Replies: 13
    Last Post: December 6th, 2012, 01:05 PM
  2. Kindly Review My Code :-) Thanks in advance
    By bhuppi in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 27th, 2012, 11:10 AM
  3. [Help] Problem with Class arrays, adding/editing and deleting
    By Grant_Searle in forum Object Oriented Programming
    Replies: 7
    Last Post: December 16th, 2011, 10:10 AM
  4. Java coding for writing telephone bill calculator program
    By eyeore in forum What's Wrong With My Code?
    Replies: 2
    Last Post: September 8th, 2009, 11:06 AM