Está en la página 1de 17

package co.madesoft.db; import java.sql.

*; public class DbConnection { static String bd = "inventario"; static String login = "root"; static String password = ""; static String url = "jdbc:mysql://localhost/"+bd; Connection conn = null; public DbConnection() { try{ Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url,login,password); if (conn!=null){ System.out.println("Coneccin a base de datos

"+bd+" OK");

} }catch(SQLException e){ System.out.println(e); }catch(ClassNotFoundException e){ System.out.println(e); } } public Connection getConeccion(){ return conn; } public void desconectar(){ conn = null; } }

package co.madesoft.db; import java.sql.*; public class DbRol { DbConnection cn; public DbRol() { cn = new DbConnection(); } public Object[][] getRoles(){ int registros = 0; try{ Statement stm = cn.getConeccion().createStatement(); PreparedStatement pstm = cn.getConeccion().prepareStatement("SELECT count(1) as cont" + " FROM rol "); ResultSet res = pstm.executeQuery(); res.next(); registros = res.getInt("cont"); res.close(); }catch(SQLException e){ System.out.println(e); } Object [][] data = new Object[registros][2]; try{ Statement stm = cn.getConeccion().createStatement(); PreparedStatement pstm = cn.getConeccion().prepareStatement("SELECT id, " + " nombre " + " FROM rol " + " ORDER BY nombre "); ResultSet res = pstm.executeQuery(); int i = 0; while(res.next()){ String id = res.getString("id"); String nombre = res.getString("nombre"); data[i][0] = id; data[i][1] = nombre; i++; } res.close(); }catch(SQLException e){ System.out.println(e); } return data; } }

package co.madesoft.db; import java.sql.*; public class DbUser { DbConnection cn; /** Creates a new instance of DbUser */ public DbUser() { cn = new DbConnection(); } public boolean valUsuario(String u, String c){ boolean r=false; try{ Statement stm = cn.getConeccion().createStatement(); PreparedStatement pstm = cn.getConeccion().prepareStatement("select count(1) as cont " + " from usuario " + " where usuario = ? " + " and clave = md5(?)"); pstm.setString(1, u); pstm.setString(2, c); ResultSet res = pstm.executeQuery(); res.next(); int cont = res.getInt("cont"); res.close(); if(cont>=1){r = true;}else{r = false;} }catch(SQLException e){ System.out.println(e); } return r;

} /** obtiene el id del usuario */ public int getIdUsuario(String u, String c){ int id = -1; try{ Statement stm = cn.getConeccion().createStatement(); PreparedStatement pstm = cn.getConeccion().prepareStatement("select id " + " from usuario " + " where usuario = ? " + " and clave = md5(?)"); pstm.setString(1, u); pstm.setString(2, c); ResultSet res = pstm.executeQuery(); res.next(); id = res.getInt("id"); res.close(); }catch(SQLException e){ System.out.println(e); }

return id; } /**obtiene las opciones del menu asocoadas al usuario */ public Object[][] getMenuUsuario(int id){ int registros = 0; try{ Statement stm = cn.getConeccion().createStatement(); PreparedStatement pstm = cn.getConeccion().prepareStatement("SELECT count(1) as cont" + " FROM opciones o,rol_usuario ru, rol_opciones ro" + " WHERE o.id=ro.id_opcion" + " and ru.id_rol = ro.id_rol" + " and ru.id_usuario = ?"); pstm.setInt(1, id); ResultSet res = pstm.executeQuery(); res.next(); registros = res.getInt("cont"); res.close(); }catch(SQLException e){ System.out.println(e); } Object [][] data = new Object[registros][5]; try{ Statement stm = cn.getConeccion().createStatement(); PreparedStatement pstm = cn.getConeccion().prepareStatement("SELECT o.nombre as nombre," + " o.nivel as nivel," + " o.id_padre as padre," + " o.id as id_menu," + " o.task as task " + " FROM opciones o,rol_usuario ru, rol_opciones ro" + " WHERE o.id=ro.id_opcion" + " and ru.id_rol = ro.id_rol" + " and ru.id_usuario = ?" + " ORDER BY o.id_padre, o.orden"); pstm.setInt(1, id); ResultSet res = pstm.executeQuery(); int i = 0; while(res.next()){ String nombre = res.getString("nombre"); String nivel = res.getString("nivel"); String padre = res.getString("padre"); String id_menu = res.getString("id_menu"); String task = res.getString("task"); data[i][0] data[i][1] data[i][2] data[i][3] data[i][4] = = = = = nombre; nivel; padre; id_menu; task;

i++; } res.close(); }catch(SQLException e){ System.out.println(e); } return data; } /** trae todos los usuarios para su administracion */ public Object[][] getUsuarios(){ int registros = 0; try{ Statement stm = cn.getConeccion().createStatement(); PreparedStatement pstm = cn.getConeccion().prepareStatement("SELECT count(1) as cont" + " FROM usuario "); ResultSet res = pstm.executeQuery(); res.next(); registros = res.getInt("cont"); res.close(); }catch(SQLException e){ System.out.println(e); } Object [][] data = new Object[registros][5]; try{ Statement stm = cn.getConeccion().createStatement(); PreparedStatement pstm = cn.getConeccion().prepareStatement("SELECT id, " + " usuario, " + " nombres, " + " apellidos," + " estado " + " FROM usuario " + " ORDER BY usuario "); ResultSet res = pstm.executeQuery(); int i = 0; while(res.next()){ String id = res.getString("id"); String usuario = res.getString("usuario"); String nombres = res.getString("nombres"); String apellidos = res.getString("apellidos"); String estado = res.getString("estado"); data[i][0] = id; data[i][1] = usuario; data[i][2] = nombres;

data[i][3] = apellidos; data[i][4] = estado; i++; } res.close(); }catch(SQLException e){ System.out.println(e); } return data; } /** actualiza un usuario */ public int updateUsuario(int id, String u, String c, String n, String a, String s, int r ){ int cont_id = -1; int cont_usuario = -1; int resultado = 0;//no hubo errores de validacion try{ Statement stm = cn.getConeccion().createStatement(); PreparedStatement pstm = cn.getConeccion().prepareStatement("select count(1) as cont " + " from usuario " + " where id = ? "); pstm.setInt(1, id); ResultSet res = pstm.executeQuery(); res.next(); cont_id = res.getInt("cont"); res.close();

cont " +

pstm = cn.getConeccion().prepareStatement("select count(1) as " from usuario " + " where usuario = ? " + " and id <> ?"); pstm.setString(1, u); pstm.setInt(2, id);

res = pstm.executeQuery(); res.next(); cont_usuario = res.getInt("cont"); res.close(); System.out.println("cont_usuario = "+cont_usuario); if(cont_id==1){ if(cont_usuario==0){ if(u.length()>0 && c.length()>0 && n.length()>0 && a.length()>0 && s.length()==1){ pstm = cn.getConeccion().prepareStatement("update usuario set usuario = ?, " + " clave = md5(?), " +

" nombres = ?, " + " apellidos = ?, " + " estado = ? " + " where id = ? "); pstm.setString(1, u); pstm.setString(2, c); pstm.setString(3, n); pstm.setString(4, a); pstm.setString(5, s); pstm.setInt(6, id); pstm.executeUpdate(); pstm = cn.getConeccion().prepareStatement("delete from rol_usuario " + " where id_usuario = ? and id_rol <> 0 "); pstm.setInt(1, id); pstm.executeUpdate(); pstm = cn.getConeccion().prepareStatement("insert into rol_usuario " + " (id_rol,id_usuario) " + " values(?,?)"); pstm.setInt(1, r); pstm.setInt(2, id); pstm.executeUpdate(); }else{ resultado = 3;//valores de los campos no validos } }else{ resultado = 2;//el login ya existe } }else{ resultado = 1;//el id de usuario no existe } }catch(SQLException e){ System.out.println(e); } return resultado;

/** inserta un usuario */ public int insertUsuario(String u, String c, String n, String a, String s, int r ){ int cont_usuario = -1; int resultado = 0;//no hubo errores de validacion try{ Statement stm = cn.getConeccion().createStatement(); PreparedStatement pstm = cn.getConeccion().prepareStatement("select count(1) as cont " + " from usuario " + " where usuario = ? "); pstm.setString(1, u); ResultSet res = pstm.executeQuery();

res.next(); cont_usuario = res.getInt("cont"); res.close(); if(cont_usuario==0){ if(u.length()>0 && c.length()>0 && n.length()>0 && a.length()>0 && s.length()==1){ pstm = cn.getConeccion().prepareStatement("insert into usuario " + " (usuario,clave,nombres,apellidos,estado) " + " values(?,md5(?),?,?,?)"); pstm.setString(1, u); pstm.setString(2, c); pstm.setString(3, n); pstm.setString(4, a); pstm.setString(5, s); pstm.executeUpdate(); " + pstm = cn.getConeccion().prepareStatement("select id " from usuario " + " where usuario = ? " + " and clave = md5(?)"); pstm.setString(1, u); pstm.setString(2, c); res = pstm.executeQuery(); res.next(); resultado = res.getInt("id"); res.close(); pstm = cn.getConeccion().prepareStatement("insert into rol_usuario " + " (id_rol,id_usuario) " + " values(?,?)"); pstm.setInt(1, r); pstm.setInt(2, resultado); pstm.executeUpdate(); pstm = cn.getConeccion().prepareStatement("insert into rol_usuario " + " (id_rol,id_usuario) " + " values(0,?)"); pstm.setInt(1, resultado); pstm.executeUpdate();

}else{ resultado = -3;//valores de los campos no validos } }else{ resultado = -2;//el login ya existe } }catch(SQLException e){ System.out.println(e);

} return resultado;

/** inserta un usuario */ public int deleteUsuario(int id){ int cont_usuario = -1; int resultado = 0;//no hubo errores de validacion try{ Statement stm = cn.getConeccion().createStatement(); PreparedStatement pstm = cn.getConeccion().prepareStatement("select count(1) as cont " + " from usuario " + " where id = ? "); pstm.setInt(1, id); ResultSet res = pstm.executeQuery(); res.next(); cont_usuario = res.getInt("cont"); res.close(); if(cont_usuario==1){ usuario " + pstm = cn.getConeccion().prepareStatement("delete from " where id = ? "); pstm.setInt(1, id); pstm.executeUpdate(); pstm = cn.getConeccion().prepareStatement("delete from rol_usuario " + " where id_usuario = ? "); pstm.setInt(1, id); pstm.executeUpdate();

}else{ resultado = -2;//el id no existe } }catch(SQLException e){ System.out.println(e); } return resultado; } }

package co.madesoft.gui; import import import import javax.swing.*; java.awt.*; java.awt.event.*; co.madesoft.db.*;

public class GuiInicio implements ActionListener{ JFrame frame; JPanel pnlCampos,pnlBotones; JLabel jlbUsuario,jlbClave; JTextField jtfUsuario; JPasswordField jpfClave; JButton jbtAceptar,jbtCancelar; public GuiInicio() { frame = new JFrame("Login de usuario"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pnlCampos = new JPanel(new GridLayout(2,2)); pnlBotones = new JPanel(new GridLayout(1,2)); jlbUsuario = new JLabel("Usuario",SwingConstants.RIGHT); jlbClave = new JLabel("Clave",SwingConstants.RIGHT); jtfUsuario = new JTextField(5); jpfClave = new JPasswordField(5); jbtAceptar = new JButton("Aceptar"); jbtAceptar.addActionListener(this); jbtCancelar = new JButton("Cancelar"); jbtCancelar.addActionListener(this); frame.getRootPane().setDefaultButton(jbtAceptar); pnlCampos.add(jlbUsuario); pnlCampos.add(jtfUsuario); pnlCampos.add(jlbClave); pnlCampos.add(jpfClave); pnlBotones.add(jbtAceptar); pnlBotones.add(jbtCancelar); frame.getContentPane().add(pnlCampos,BorderLayout.NORTH); frame.getContentPane().add(pnlBotones,BorderLayout.EAST); frame.pack(); frame.setLocationRelativeTo(frame.getParent()); frame.setVisible(true);

public void actionPerformed(ActionEvent e) { if(e.getSource()==jbtCancelar){System.exit(0);} if(e.getSource()==jbtAceptar){ DbUser us = new DbUser(); boolean v = us.valUsuario(jtfUsuario.getText(), String.copyValueOf(jpfClave.getPassword())); if(v==true){

int id = us.getIdUsuario(jtfUsuario.getText(), String.copyValueOf(jpfClave.getPassword())); GuiPrincipal p = new GuiPrincipal(jtfUsuario.getText(),id); frame.setVisible(false); }else{ jtfUsuario.setText(""); jpfClave.setText(""); } } } public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); GuiInicio g = new GuiInicio(); } }

package co.madesoft.gui; import import import import import javax.swing.*; co.madesoft.db.*; java.awt.*; java.awt.event.*; co.madesoft.gui.user.*;

public class GuiPrincipal implements ActionListener{ String usuario,clave; JFrame frame; JLabel jlbUsuario; JMenuBar menuBar; JMenu menu, submenu; JMenuItem menuItem; Object[][] data; /** Creates a new instance of GuiPrincipal */ public GuiPrincipal(String u,int id) { usuario = u; frame = new JFrame(usuario); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); DbUser us = new DbUser(); menuBar = new JMenuBar(); frame.setJMenuBar(menuBar); data = us.getMenuUsuario(id); for (int f=0;f<data.length;f++){ int m = 0; if(String.valueOf(data[f][1]).equals("0")){ menu = new JMenu(String.valueOf(data[f][0])); menuBar.add(menu); for (int h=0;h<data.length;h++){ if(String.valueOf(data[h][1]).equals("1") && data[h] [2].equals(data[f][3])){ menuItem = new JMenuItem(String.valueOf(data[h] [0])); menuItem.addActionListener(this); menu.add(menuItem); } } m++; } } jlbUsuario = new JLabel(new ImageIcon("cajas.jpg")); frame.getContentPane().add(jlbUsuario,BorderLayout.CENTER); frame.getContentPane().setBackground(new Color(255,255,255)); frame.pack(); //frame.setSize(800,600); frame.setExtendedState(JFrame.MAXIMIZED_BOTH); frame.setLocationRelativeTo(frame.getParent());

frame.setVisible(true); } public void actionPerformed(ActionEvent e) { String task = null; for (int f=0;f<data.length;f++){ if(e.getActionCommand().equals(String.valueOf(data[f][0]))){ task = String.valueOf(data[f][4]); } } //jlbUsuario.setText(task); if(task.equals("Salir")){ System.exit(0); } //clsSesion if(task.equals("clsSesion")){ frame.setVisible(false); GuiInicio gi = new GuiInicio(); } if(task.equals("admUsuario")){ AdmUsuarios ua = new AdmUsuarios(); } if(task.equals("admRol")){ AdmRoles ua = new AdmRoles(); } } }

package co.madesoft.gui.user; import import import import import javax.swing.*; javax.swing.table.*; java.awt.*; java.awt.event.*; co.madesoft.db.*;

public class AdmUsuarios implements ActionListener{ JFrame frame; JScrollPane spnTabla; DefaultTableModel dtm; JTable jtbUsuarios; JPanel pnlBotones,pnlUsuario,pnlPanel; JLabel lblId,lblUsuario,lblClave,lblNombres,lblApellidos,lblEstado,lblRoles; JTextField txtId,txtUsuario,txtNombres,txtApellidos,txtEstado; JPasswordField jpfClave; JButton btnAgregar, btnEditar, btnBorrar; JComboBox cmbRoles; Object[][] data; Object[][] dtRoles; String[] strNombreRol; DbUser us = new DbUser(); DbRol rol = new DbRol(); int fila = -1;//fila afectada para editar usuarios /** Creates a new instance of GuiUserAdmin */ public AdmUsuarios() { frame = new JFrame("Administrar Usuarios"); //DbUser us = new DbUser(); data = us.getUsuarios(); String[] columNames = {"id","usuario","nombres","apellidos","estados"}; dtm= new DefaultTableModel(data, columNames); jtbUsuarios = new JTable(dtm); jtbUsuarios.setPreferredScrollableViewportSize(new Dimension(500, 150)); spnTabla = new JScrollPane(jtbUsuarios);

lblId = new JLabel("Id"); lblUsuario = new JLabel("Usuario"); lblClave = new JLabel("Clave"); lblNombres = new JLabel("Nombres"); lblApellidos = new JLabel("Apellidos"); lblEstado = new JLabel("Estado"); lblRoles= new JLabel("Rol");

txtId = new JTextField(10); txtUsuario = new JTextField(10); txtNombres = new JTextField(10); txtApellidos = new JTextField(10); txtEstado = new JTextField(10); jpfClave = new JPasswordField(10); dtRoles = rol.getRoles(); strNombreRol = new String[dtRoles.length]; for(int a=0;a<dtRoles.length;a++){ strNombreRol[a]=String.valueOf(dtRoles[a][1]); } cmbRoles = new JComboBox(strNombreRol); pnlUsuario = new JPanel(new GridLayout(7,2)); pnlUsuario.add(lblId); pnlUsuario.add(txtId); pnlUsuario.add(lblUsuario); pnlUsuario.add(txtUsuario); pnlUsuario.add(lblClave); pnlUsuario.add(jpfClave); pnlUsuario.add(lblNombres); pnlUsuario.add(txtNombres); pnlUsuario.add(lblApellidos); pnlUsuario.add(txtApellidos); pnlUsuario.add(lblEstado); pnlUsuario.add(txtEstado); pnlUsuario.add(lblRoles); pnlUsuario.add(cmbRoles); btnAgregar = new JButton("Agregar"); btnEditar = new JButton("Editar"); btnBorrar = new JButton("Borrar"); btnAgregar.addActionListener(this); btnEditar.addActionListener(this); btnBorrar.addActionListener(this); pnlBotones = new JPanel(new GridLayout(1,3)); pnlBotones.add(btnAgregar); pnlBotones.add(btnEditar); pnlBotones.add(btnBorrar);

jtbUsuarios.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e){ fila = jtbUsuarios.rowAtPoint(e.getPoint()); int columna = jtbUsuarios.columnAtPoint(e.getPoint()); if ((fila > -1) && (columna > -1)){ txtId.setText(String.valueOf(jtbUsuarios.getValueAt(f ila,0)));

txtUsuario.setText(String.valueOf(jtbUsuarios.getValu eAt(fila,1))); eAt(fila,2))); lueAt(fila,3))); At(fila,4))); }); } } txtNombres.setText(String.valueOf(jtbUsuarios.getValu txtApellidos.setText(String.valueOf(jtbUsuarios.getVa txtEstado.setText(String.valueOf(jtbUsuarios.getValue

frame.getContentPane().add(spnTabla,BorderLayout.NORTH); frame.getContentPane().add(pnlUsuario,BorderLayout.CENTER); frame.getContentPane().add(pnlBotones,BorderLayout.SOUTH); frame.pack(); frame.setResizable(false); frame.setLocationRelativeTo(frame.getParent()); frame.setVisible(true); } public void limpiarCampos(){ txtId.setText(""); txtUsuario.setText(""); jpfClave.setText(""); txtNombres.setText(""); txtApellidos.setText(""); txtEstado.setText(""); } public void actionPerformed(ActionEvent e){ int resultado = -1; if(e.getSource()==btnEditar){ int i = Integer.parseInt(txtId.getText()); String u = txtUsuario.getText(); String c = String.copyValueOf(jpfClave.getPassword()); String n = txtNombres.getText(); String a = txtApellidos.getText(); String s = txtEstado.getText(); int index = cmbRoles.getSelectedIndex(); int r = (int)(Integer.parseInt(String.valueOf(dtRoles[index] [0]))); resultado = us.updateUsuario(i,u,c,n,a,s,r); if(resultado==0){ dtm.setValueAt(u,fila,1); dtm.setValueAt(n,fila,2); dtm.setValueAt(a,fila,3); dtm.setValueAt(s,fila,4); limpiarCampos(); } } //insertUsuario

if(e.getSource()==btnAgregar){ String u = txtUsuario.getText(); String c = String.copyValueOf(jpfClave.getPassword()); String n = txtNombres.getText(); String a = txtApellidos.getText(); String s = txtEstado.getText(); int index = cmbRoles.getSelectedIndex(); int r = (int)(Integer.parseInt(String.valueOf(dtRoles[index] [0]))); resultado = us.insertUsuario(u,c,n,a,s,r); if(resultado>0){ Object[] newRow={resultado,u,n,a,s}; dtm.addRow(newRow); limpiarCampos(); }

//deleteUsuario(int id) if(e.getSource()==btnBorrar){ int i = Integer.parseInt(txtId.getText()); resultado = us.deleteUsuario(i); if(resultado==0){ dtm.removeRow(fila); limpiarCampos(); } } System.out.println(resultado); }

También podría gustarte