28/11/05

* Nuevo sabotaje : PC de los puestos ( al menos antes así se llamaban ) pc102 y pc111 , sin red ¿?. ¿Por la tarde/noche no saben dejar las cosas como estaban?.
   
Estadisticas y contadores web gratis
Manuales Oposiciones
   
   

El código : Menu1.java

Si tienes bloqueados los elementos emergentes (pop ups) no funcionará el Applet


Continuamos con Java & MySQL:

1.- Instalar driver-connector de Java y MySQL :Link para bajrse el connector de Java y MySQL, tras instalrlo ir a 2.

2.- Configurar el ODBC de Windows para tu BBDD( si es que trabajas desde este so ): Panel de control > Herramientas administrativas > ODBC

Damos a agregar

definimos nuestra base de datos ( se supone ya creada en MySQL, si no trabajar con la que MySQL proporciona para pruebas test)

luego OK , y aceptar.

3.- Ejecutar JDBCTest para testear una BBDD y generar el código que es lo que nos interesa:

 Link muy bueno , donde Roberto nos explica como usar la utilidad de Sun para testear BBDD y generar código

Desde este link Roberto nos explica como bajarnos el JDBCTest1_03 de Sun , Para testear bases de datos, como instalarlo y ejecutarlo, vamos a resumirlo , pero aconsejo irse a "las fuentes"

 

 

Como deciamos el otro día lo 1º es registrar el driver:

pero antes define el CLASSPATH donde están las clases , tanto del connector ( driver) y de el Test de Sun en mi caso :

set CLASSPATH=.;C:\java\JDBCTest1_03\JDBCTest1_03\classes;

C:\mentor\MySql\mysql-connector-java-3.1.11\mysql-connector-java-3.1.11\mysql-connector-java-3.1.11-bin.jar;

Desde la shell de dos: > C:\Documents and Settings\mua>java -classpath .;%classpath%;C:\mentor\MySql\mysql-connector-java-3.1.11\mysql-connector-java-3.1.11\mysql-connector-java-3.1.11-bin.jar JDBCTest

luego: Driver>Register driver > (nueva ventana) ok

// REGISTER DRIVER
try {Driver d = (Driver)Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();}

 catch (Exception e) {System.out.println(e)}
 


2. Seleccionar el driver

// SELECT DRIVER
try {
while (en.hasMoreElements()){
d = (Driver)en.nextElement();
if (d.getClass().getName().equals(value)){
return d;
}
} catch (Exception e) {
System.out.println(e)
}
 


Creamos un statement

 // CREATE STATEMENT
Statement stmt;
try {
stmt = con.createStatement();
} catch (Exception e){
System.out.println(e);
}

Y ejecutamos una consulta

 // EXECUTE QUERY
ResultSet results;
try {
results = stmt.executeQuery("select * from alumnos ;")
} catch (Exception e){
System.out.println(e);
}

 

 

Le damos a Show results

// GET ALL RESULTS
StringBuffer buf = new StringBuffer();
try {
ResultSetMetaData rsmd = results.getMetaData();
int numCols = rsmd.getColumnCount();
int i, rowcount = 0;

// get column header info
for (i=1; i <= numCols; i++){
if (i > 1) buf.append(",");
buf.append(rsmd.getColumnLabel(i));
}
buf.append("\n");

// break it off at 100 rows max
while (results.next() && rowcount < 100){
// Loop through each column, getting the column
// data and displaying

for (i=1; i <= numCols; i++) {
if (i > 1) buf.append(",");
buf.append(results.getString(i));
}
buf.append("\n");
rowcount++;
}
results.close();
} catch (Exception e) {
System.out.println(e);
return;
}


Con lo que a traves de este ejercicio obtenemos unos cuantos ladrillos para construir una aplicación con acceso a bbdd MySQL

Los Ladrillos:

// REGISTER DRIVER
try {
    Driver d = (Driver)Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
} catch (Exception e) {
    System.out.println(e)
}
// GET CONNECTION WARNINGS
SQLWarning warning = null;
try {
    warning = con.getWarnings();

    if (warning == null){
        System.out.println("No Warnings");
        return;
    }

    while (warning != null) {
        System.out.println("Warning: "+warning);
        warning = warning.getNextWarning();
    }
} catch (Exception e){
    System.out.println(e);
}
 // CREATE STATEMENT 
Statement stmt;
try {
    stmt = con.createStatement();
} catch (Exception e){
    System.out.println(e);
}
 // EXECUTE QUERY 
ResultSet results;
try {
    results = stmt.executeQuery("select * from alumnos ;")
} catch (Exception e){
    System.out.println(e);
}
// GET ALL RESULTS 
StringBuffer buf = new StringBuffer();
try {
    ResultSetMetaData rsmd = results.getMetaData();
    int numCols = rsmd.getColumnCount();
    int i, rowcount = 0;

   // get column header info
    for (i=1; i <= numCols; i++){
        if (i > 1) buf.append(",");
        buf.append(rsmd.getColumnLabel(i));
    }
    buf.append("\n");

    // break it off at 100 rows max
    while (results.next() && rowcount < 100){
        // Loop through each column, getting the column
        // data and displaying

        for (i=1; i <= numCols; i++) {
            if (i > 1) buf.append(",");
            buf.append(results.getString(i));
        }
        buf.append("\n");
        rowcount++;
    }
    results.close();
} catch (Exception e) {
    System.out.println(e);
    return;
}
// IS CONNECTION CLOSED 
boolean b;
try {
    b = con.isClosed();
} catch (Exception e) {
    System.out.println(e);
// GET UPDATE COUNT 
int i;
try {
    i = stmt.getUpdateCount();
} catch (Exception e) {
    System.out.println(e);
}
}
// CLOSE CONNECTION 
try {
    con.close();
} catch (Exception e) {
    System.out.println(e);
}

Lo probamos en el siguiente código:

  import java.sql.*; // SQL library!

public class AccesoBBDD1
{
public static void main (String array[])
{
AccesoBBDD1 instancia = new AccesoBBDD1();
instancia.ejecuta();
}

void depura(String mensaje)
{
System.out.println(mensaje);
}

void ejecuta()
{
depura("Empezamos");

// REGISTER DRIVER
try {
Driver d = (Driver)Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
} catch (Exception e) {
System.out.println(e);
}


// GET CONNECTION
Connection con = null;
try
{
depura("Recuperamos conexión");
con = DriverManager.getConnection("jdbc:odbc:prueba1","","");
}
catch(Exception e)
{
System.out.println(e);
}

// GET CONNECTION WARNINGS
SQLWarning warning = null;
try
{
warning = con.getWarnings();

if (warning == null)
{
System.out.println("No Warnings");
// return;
}

while (warning != null)
{
System.out.println("Warning: "+warning);
warning = warning.getNextWarning();
}
}
catch (Exception e)
{
System.out.println(e);
}

// CREATE STATEMENT
Statement stmt = null;
try
{
stmt = con.createStatement();
}
catch (Exception e)
{
System.out.println(e);
}

// EXECUTE QUERY
ResultSet results = null;
try
{
results = stmt.executeQuery("select * from alumnos");
}
catch (Exception e)
{
System.out.println(e);
}

// GET ALL RESULTS
StringBuffer buf = new StringBuffer();

try
{
ResultSetMetaData rsmd = results.getMetaData();
int numCols = rsmd.getColumnCount();
int i, rowcount = 0;

// get column header info
for (i=1; i <= numCols; i++)
{
if (i > 1) buf.append(",");
buf.append(rsmd.getColumnLabel(i));
}
buf.append("\n");

// break it off at 100 rows max
while (results.next() && rowcount < 100)
{
// Loop through each column, getting the column
// data and displaying

for (i=1; i <= numCols; i++)
{
if (i > 1) buf.append(",");
buf.append(results.getString(i));
}
buf.append("\n");
rowcount++;
}

System.out.println(buf);

results.close();
}
catch (Exception e)
{
System.out.println(e);
return;
}

depura("Finalizamos");
}
}
 

:Lo ejecutamos con jCreator

   
   Vamos a crear otra BBDD: prueba2 , con una tabla de mascotas , por ahora.

Apliquemos un poco de SQL para MySQL, para crear una BBDD y una tabla:

CREATE DATABASE TiendaAnimales;

CREATE TABLE `TiendaAnimales`.`mascotas` (
`index` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`nombre` VARCHAR(45) NOT NULL DEFAULT '',
`propietario` VARCHAR(45) DEFAULT '',
`especie` VARCHAR(45) NOT NULL DEFAULT '',
`sexo` CHAR(1) NOT NULL DEFAULT '',
`nacimiento` DATETIME NOT NULL DEFAULT 0,
`muerte` DATETIME NOT NULL DEFAULT 0,
PRIMARY KEY(`index`)
)
ENGINE = InnoDB;

//pero vamos a alterar la estructura de la tabla

ALTER TABLE `tiendaanimales`.`mascotas` MODIFY COLUMN `nacimiento` DATE,
MODIFY COLUMN `muerte` DATE;

//introducimos unos registro

INSERT INTO tiendaanimales.mascotas VALUES (1,'Puffball','Diane','hamster','f','1999-03-30',Null);

INSERT INTO tiendaanimales.mascotas VALUES (2,'Tom','Diane','raton','m','1960-05-22',Null);

INSERT INTO tiendaanimales.mascotas VALUES (3,'Jerry','Cristina','gato','m','1965-08-11',Null);

INSERT INTO tiendaanimales.mascotas VALUES (4,'rintinti','Javier','perro','m','1965-11-08','1975-08-11');

//Veamos una consulta de todas las mascotas con todos sus campos:

select * from tiendaanimales.mascotas ;

Si ejecuto el código anterior para esta bbdd :


Sea el JFrame siguiente:  TestBBDDFrame1.java

(nota :el driver ODBC se llama mysql)

/*
 * TestBBDDFrame1.java
 *
 * Created on 27 de noviembre de 2005, 23:32
 */

/**
 * powered by NetBeans 4.1
 * @author  javcasta2002@yahoo.com - http://javcasta.bounceme.net 
 */
import java.sql.*;
public class TestBBDDFrame1 extends javax.swing.JFrame {
    public Connection con ;
    public Statement stmt ;
    /** Creates new form TestBBDDFrame1 */
    public TestBBDDFrame1() {
        initComponents();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();

        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        jButton1.setText("Conectar a BBDD");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 0, 360, -1));

        jButton2.setText("Ejecutar consulta");
        jButton2.setEnabled(false);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 30, -1, -1));

        jTextField1.setEditable(false);
        jTextField1.setText("select * from mascotas");
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        getContentPane().add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 30, 230, -1));

        jTextArea1.setColumns(100);
        jTextArea1.setRows(50);
        getContentPane().add(jTextArea1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 60, -1, 190));

        jLabel1.setText("Estado: No conectado a BBDD");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(4, 280, 370, -1));

        pack();
    }
    // </editor-fold>
    
      
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
        try{resultado();} catch(Exception e){}
    }
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
        try{AccesoBBDD1();
        jButton2.setEnabled(true);
        jTextField1.setEditable(true);} catch(Exception e){}
        
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TestBBDDFrame1().setVisible(true);
            }
        });
        
    }
//Método
    public void AccesoBBDD1() {
        
        
        
// REGISTER DRIVER
        try {
            Driver d = (Driver)Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
        } catch (Exception e) {
            //System.out.println(e);
            jLabel1.setText("Estado:Error de driver"+e);
        }
        
        
// GET CONNECTION
        con = null;
        try {
            
            con = DriverManager.getConnection("jdbc:odbc:mysql","","");
        } catch(Exception e) {
//System.out.println(e);
            jLabel1.setText("Estado:Error de conexion"+e);
        }
        
// GET CONNECTION WARNINGS
        SQLWarning warning = null;
        try {
            warning = con.getWarnings();
            
            if (warning == null) {
//System.out.println("No Warnings");
                jLabel1.setText("Estado:No Warnings");
// return;
            }
            
            while (warning != null) {
//System.out.println("Warning: "+warning);
                jLabel1.setText("Estado: Warning - "+warning);
                warning = warning.getNextWarning();
            }
        } catch (Exception e) {
//System.out.println(e);
            jLabel1.setText("Estado:Error de warning"+e);
        }//fin método
        
        
        
        
    }
    //Método
// GET ALL RESULTS
    public void resultado(){
        // CREATE STATEMENT
        stmt = null;
        try {
            stmt = con.createStatement();
        } catch (Exception e) {
//System.out.println(e);
            jLabel1.setText("Estado:Error al crear statement"+e);
        }
        // EXECUTE QUERY
        ResultSet results = null;
        try {
            results = stmt.executeQuery(jTextField1.getText());
        } catch (Exception e) {
//System.out.println(e);
            jLabel1.setText("Estado:consulta"+e);
        }
        StringBuffer buf = new StringBuffer();
        
        try {
            ResultSetMetaData rsmd = results.getMetaData();
//jLabel2.setText("ResultSetMetaData rsmd = results.getMetaData();");
            int numCols = rsmd.getColumnCount();
            Integer lascol=numCols;
//jLabel2.setText(lascol.toString());
            int i, rowcount = 0;
            
// get column header info
            for (i=1; i <= numCols; i++) {
                if (i > 1) buf.append(",");
                buf.append(rsmd.getColumnLabel(i));
            }
            buf.append("\n");
            
// break it off at 100 rows max
            while (results.next() && rowcount < 100) {
// Loop through each column, getting the column
// data and displaying
                
                for (i=1; i <= numCols; i++) {
                    if (i > 1) buf.append(",");
                    buf.append(results.getString(i));
                }
                buf.append("\n");
                rowcount++;
            }
            
//System.out.println(buf);
            jTextArea1.setText(buf.toString());
            
            results.close();
        } catch (Exception e) {
//System.out.println(e);
            jLabel1.setText("Estado:final"+e);
            return;
        }
        
        
    }//fin método
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration
    
}

 

 
 

Otra forma de referenciar el driver de acceso a BBDD de MySQL, sin necesidad de configurar ODBC

Nos bajamos el mysql-connector-java-4.1.11.zip

Lo descomprimimos en C:\Archivos de programa\Java\jdk1.5.0_05\jre\lib\ext\mysql-connector-java-3.1.11-bin.jar

Esto se muestra en el siguiente código : que va a crear una tabla en la bbdd CafeBaseDatos ( ya creada , of course !)

1.- Creamos la BBDD en MySQL

2.- Cargar el driver , en Java

3.- Establecer la conexión , en Java

4.- Crear un statement

5.- Ejecutamos una sentencia de sql

 

import java.sql.*;

public class CreateCoffees {
    public static void main(String args[]) {
        //String url = "jdbc:mySubprotocol:myDataSource";
        String url = "jdbc:mysql://localhost/cafebasedatos"
        Connection con;
        String createString;
        createString = "create table COFFEES " +
                            "(COF_NAME VARCHAR(32), " +
                            "SUP_ID INTEGER, " +
                            "PRICE FLOAT, " +
                            "SALES INTEGER, " +
                            "TOTAL INTEGER)";
        Statement stmt;

        try { //Cargamos el driver
            Class.forName("com.mysql.jdbc.Driver");
        } catch(java.lang.ClassNotFoundException e) {
            System.err.print("ClassNotFoundException: ");
            System.err.println(e.getMessage());
        }

        try { //Establecemos la conexión
            //con = DriverManager.getConnection(url, "myLogin", "myPassword");
            con = DriverManager.getConnection(url, "root", "mysql");
            //Creamos el ststement
            stmt = con.createStatement();
            //Ejecuta una actualización: crear tablas , insertar , delete ,...
            stmt.executeUpdate(createString);
            stmt.close();
            con.close();
            // stmt.executeQuery() : consultas (select)
        } catch(SQLException ex) {
            System.err.println("SQLException: " + ex.getMessage());
        }
    }
}

Por ejemplo para que el código anterior nos inserte dos registro:

....

createstring = " INSERT INTO coffees VALUES ('Colombia',101,7.99,0,0),('JSP',123,8.66,0,0)";

....

// en lugar de stmt.executeUpdate(createstring);

stmt.executeQuery(createstring);


O incluso pasar un fichero a la tabla seria:

....

createstring = " LOAD DATA LOCAL INFILE 'c:/cafe.txt' INTO TABLE coffees";

....

stmt.executeUpdate(createstring);

//stmt.executeQuery(createstring);


 

En http://java.sun.com/j2se/1.5.0/docs/api/java/sql/Statement.html Tenemos el constructor y los métodos de statement


Pero para recoger resultados de consultas necesitamos un objeto ResultSet

 

....

createstring = " select COF_NAME,PRICE from coffees";

....

//stmt.executeUpdate(createstring);

//stmt.executeQuery(createstring);

ResultSet rs = stmt.executeQuery(createstring);

while (rs.next()){

   String s = rs.getString("COF_NAME");

   Float n = rs.getFloat("PRICE");

   System.out.println(s+" "+n);

   } //fin while


Uso del Objeto PreparedStatement

Si se va a ejecutar muchas veces un objeto Statement, reduciremos el tiempo de ejecución si usamos el objeto PreparedStatement, y además puede usar variables. Ejemplo:

 

PreparedStatement updateSales = con.prepareStatement("Update coffes set sales =? where COF_NAME like ?");

updateSales.setInt(1,75);

updateSales.setString(2,"Colombian");

updateSales.executeUpdate();