Vous êtes sur la page 1sur 12

Conexin de una BD de MySQL y JAVA

En este ejemplo vamos a conectar una BD con Java de tal manera de que nos de cmo resultado una aplicacin como la siguiente.

Figura1

Para este propsito tenemos que instalar en primer lugar el manejador de BD MySQL una vez instalado tenemos que crear una BD de nombre prueba1 y una tabla con los siguientes campos CREATE TABLE `datos` ( `id` smallint(5) unsigned NOT NULL auto_increment, `vcNombre` varchar(255) NOT NULL default '', `vcDom` varchar(255) NOT NULL default '', `vcTel` varchar(255) NOT NULL default '', `vcEmail` varchar(255) NOT NULL default '', UNIQUE KEY `id` (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ; Insertar registros para la realizacin de algunas pruebas con la siguiente instruccin INSERT INTO `datos` VALUES (1, 'beto', 'tabasco', 'enai', 'gsggs'); Una vez creada la BD lo siguiente es instalar la aplicacin de NetBeans IDE 5.0 Una vez instalada la aplicacin se tiene que instalar el controlador de la BD JDBC : De nombre mysql-connector-java-3.0.11-stable-bin en la siguiente ruta C:\Archivos de programa\Java\jdk1.5.0_06\jre\lib\ext MIS y MCCC Roberto Castillo Ortega
Conexin de una BD de MySQL y JAVA

Una vez instalado el controlador se procede a crear el GUI a travs de NetBeans Como el de la Figura1 Primero que nada una vez creada la GUI procedemos a importar la clase sql de la siguiente manera import java.sql.*; Lo siguiente es crear el mtodo para establecer la conexin private void initConnection() { try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); con = DriverManager.getConnection( "jdbc:mysql://localhost/prueba1","root","" ); } catch( Exception e ){ javax.swing.JOptionPane.showMessageDialog(this, e, "Error",javax.swing.JOptionPane.ERROR_MESSAGE); } // fin del catch }

El cdigo final es el siguiente:

package bdpruebas; import java.sql.*; /** * * @author roberto */ public class NewJFrame extends javax.swing.JFrame { private Object[] options = {"SI", "NO"}; private int iNumRows; private String url = "jdbc:odbc:prueba1"; private Connection con; private Statement s; public ResultSet rs; public boolean agre= false; public boolean modif=false; /** Creates new form NewJFrame */ MIS y MCCC Roberto Castillo Ortega
Conexin de una BD de MySQL y JAVA

public NewJFrame() { initComponents(); initConnection(); getData(); setTxtText(); }

// <editor-fold defaultstate="collapsed" desc=" Generated Code "> private void initComponents() { jFrame1 = new javax.swing.JFrame(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); txtNom = new javax.swing.JTextField(); txtDir = new javax.swing.JTextField(); txtTel = new javax.swing.JTextField(); txteml = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); jButton6 = new javax.swing.JButton(); jButton7 = new javax.swing.JButton(); jButton8 = new javax.swing.JButton(); jButton9 = new javax.swing.JButton(); org.jdesktop.layout.GroupLayout jFrame1Layout = new org.jdesktop.layout.GroupLayout(jFrame1.getContentPane()); jFrame1.getContentPane().setLayout(jFrame1Layout); jFrame1Layout.setHorizontalGroup( jFrame1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(0, 400, Short.MAX_VALUE) ); jFrame1Layout.setVerticalGroup( jFrame1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(0, 300, Short.MAX_VALUE) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("clave"); jLabel2.setText("Nombre"); jLabel3.setText("direccion"); MIS y MCCC Roberto Castillo Ortega
Conexin de una BD de MySQL y JAVA

jLabel4.setText("telefono"); jLabel5.setText("email"); jTextField1.setEditable(false); txtDir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtDirActionPerformed(evt); } }); jButton1.setText("|<"); jButton1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton1MouseClicked(evt); } }); jButton2.setText(">>"); jButton2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton2MouseClicked(evt); } }); jButton3.setText("<<"); jButton3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton3MouseClicked(evt); } }); jButton4.setText(">|"); jButton4.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton4MouseClicked(evt); } }); jButton5.setText("Agregar"); jButton5.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton5MouseClicked(evt); } }); jButton6.setText("Guardar"); jButton6.addMouseListener(new java.awt.event.MouseAdapter() { MIS y MCCC Roberto Castillo Ortega
Conexin de una BD de MySQL y JAVA

public void mouseClicked(java.awt.event.MouseEvent evt) { jButton6MouseClicked(evt); } }); jButton7.setText("Eliminar"); jButton8.setText("cancelar"); jButton8.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton8MouseClicked(evt); } }); jButton9.setText("modificar"); jButton9.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton9MouseClicked(evt); } }); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(37, 37, 37) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jLabel1) .add(jLabel2) .add(jLabel3) .add(jLabel4) .add(jLabel5)) .add(44, 44, 44) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) .add(txteml) .add(txtTel) .add(txtDir) .add(txtNom) .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 175, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .add(layout.createSequentialGroup() .add(50, 50, 50) .add(jButton1) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jButton2) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) MIS y MCCC Roberto Castillo Ortega
Conexin de una BD de MySQL y JAVA

.add(jButton3) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jButton4))) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 67, Short.MAX_VALUE) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jButton7) .add(jButton8) .add(jButton9) .add(jButton6) .add(jButton5)) .add(55, 55, 55)) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addContainerGap() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(jLabel1) .add(15, 15, 15) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel2) .add(txtNom, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(19, 19, 19) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(jLabel3) .add(27, 27, 27) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel4) .add(txtTel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(22, 22, 22) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel5) .add(txteml, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .add(txtDir, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(16, 16, 16) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jButton1) MIS y MCCC Roberto Castillo Ortega
Conexin de una BD de MySQL y JAVA

.add(jButton2) .add(jButton3) .add(jButton4)) .addContainerGap(118, Short.MAX_VALUE)) .add(layout.createSequentialGroup() .add(29, 29, 29) .add(jButton5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jButton9, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(17, 17, 17) .add(jButton6, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(16, 16, 16) .add(jButton7, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 16, Short.MAX_VALUE) .add(jButton8, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(137, 137, 137)) ); pack(); }// </editor-fold> private void jButton8MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: } private void jButton9MouseClicked(java.awt.event.MouseEvent evt) { modif=true; } ////////////////////////////// private void jButton6MouseClicked(java.awt.event.MouseEvent evt) { if (agre==true){ try{ String insertString = "INSERT INTO datos (vcNombre, vcDom, vcTel, vcEmail) VALUES(" + "'" + txtNom.getText() + "'," + "'" + txtDir.getText() + "'," + "'" + txtTel.getText() + "'," + "'" + txteml.getText() + "')"; s.executeUpdate( insertString ); getData(); rs.last(); // en teoria debe de estar hasta el final verdad que si??? setTxtText(); javax.swing.JOptionPane.showMessageDialog(this,"Datos guardados exitsamente!", "Aviso",javax.swing.JOptionPane.INFORMATION_MESSAGE); MIS y MCCC Roberto Castillo Ortega
Conexin de una BD de MySQL y JAVA

} catch( Exception e ){ javax.swing.JOptionPane.showMessageDialog(this, e, "Error",javax.swing.JOptionPane.ERROR_MESSAGE); } } if (modif==true){ try{ int _id = rs.getInt("id"); String updateString = "UPDATE datos SET " + "vcNombre = '" + txtNom.getText() + "'," + "vcDom = '" + txtDir.getText() + "'," + "vcTel = '" + txtTel.getText() + "'," + "vcEmail = '" + txteml.getText() + "' " + "WHERE id = " + _id; s.executeUpdate( updateString ); getData(); setTxtText(); } catch( Exception e ){ javax.swing.JOptionPane.showMessageDialog(this, e, "Error",javax.swing.JOptionPane.ERROR_MESSAGE); } // fin del catch finally{ javax.swing.JOptionPane.showMessageDialog(this,"Datos actualizados exitsamente!", "Aviso",javax.swing.JOptionPane.INFORMATION_MESSAGE); } // fin de finally } } ///////////////////////////////////////// private void jButton5MouseClicked(java.awt.event.MouseEvent evt) { // limpiar clrTxtText(); agre=true; } ///////////////////////////////////////////// private void jButton4MouseClicked(java.awt.event.MouseEvent evt) { //ultimo registro try{ rs.last(); setTxtText(); } catch( Exception e ){} }

MIS y MCCC Roberto Castillo Ortega

Conexin de una BD de MySQL y JAVA

//////////////////////////////////7 private void jButton3MouseClicked(java.awt.event.MouseEvent evt) { //registro anterior try{ rs.previous(); setTxtText(); } catch( Exception e ){} } //////////////////////////////////////////////////7 private void jButton2MouseClicked(java.awt.event.MouseEvent evt) { //siguiente registro try{ rs.next(); setTxtText(); } catch( Exception e ){} } ////////////////////////////// private void jButton1MouseClicked(java.awt.event.MouseEvent evt) { //primer registro try{ rs.first(); setTxtText(); } catch( Exception e ){} } private void txtDirActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame().setVisible(true); } }); } // Variables declaration - do not modify MIS y MCCC Roberto Castillo Ortega
Conexin de una BD de MySQL y JAVA

private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButton6; private javax.swing.JButton jButton7; private javax.swing.JButton jButton8; private javax.swing.JButton jButton9; private javax.swing.JFrame jFrame1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JTextField jTextField1; private javax.swing.JTextField txtDir; private javax.swing.JTextField txtNom; private javax.swing.JTextField txtTel; private javax.swing.JTextField txteml; // End of variables declaration private void initConnection() { try{ //Class.forName( "com.mysql.jdbc.Driver" ).newInstance(); Class.forName("com.mysql.jdbc.Driver").newInstance(); con = DriverManager.getConnection( "jdbc:mysql://localhost/prueba1","root); } catch( Exception e ){ javax.swing.JOptionPane.showMessageDialog(this, e, "Error",javax.swing.JOptionPane.ERROR_MESSAGE); //System.exit(1); } // fin del catch } ///////////////////////////////////////////////////////////////////////////// private void getData(){ try{ s = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); rs = s.executeQuery( "select * from datos" ); rs.last(); iNumRows = rs.getRow(); rs.first(); } catch( Exception e ){ javax.swing.JOptionPane.showMessageDialog(this, e, "Error",javax.swing.JOptionPane.ERROR_MESSAGE); MIS y MCCC Roberto Castillo Ortega
Conexin de una BD de MySQL y JAVA

} // fin del catch } // fin de getData //////////////////////////////////////////////////////////////////////////////7 private void setTxtText(){ try{ jTextField1.setText(rs.getString("id")); txtNom.setText( rs.getString("vcNombre") ); txtDir.setText( rs.getString("vcDom") ); txtTel.setText( rs.getString("vcTel") ); txteml.setText( rs.getString("vcEmail") ); } // fin del try catch( Exception e ){ javax.swing.JOptionPane.showMessageDialog(this, e, "Error",javax.swing.JOptionPane.ERROR_MESSAGE); } } // fin de setTxtText ////////////////////////////////////////////// private void clrTxtText(){//brorrar cajas de texto try{ txtNom.setText( "" ); txtDir.setText( "" ); txtTel.setText( "" ); txteml.setText( "" ); } // fin del try catch( Exception e ){} } } //////////////////////////////////////////////////////////////////////////////////////////////////

MIS y MCCC Roberto Castillo Ortega

Conexin de una BD de MySQL y JAVA

Esta vista se activa en el men windows, opcion runtime.

El Puente JDBC-ODBC ya esta se debe de agregar el Mysql, buscando el archivo controlador en la ruta c:/archiv1/java//ext Al existir este se pueden controlar bases de datos de Microsoft Acces, SQL Server. Al existir los drivers, estas carpetas se crean al realizar una conexin, se debe de poner un host (localhost) pouerto (3306) y el nombre de la base de datos (Esto para MySql) y despus se puede manipular la base de datos.

Esta conexin se creo con el driver jdbc:ODBC, y se pone el nombre de la base de datos.

MIS y MCCC Roberto Castillo Ortega

Conexin de una BD de MySQL y JAVA

Vous aimerez peut-être aussi