Está en la página 1de 7

BASE DE DATOS ACCESS EN JAVA SIN REGISTRO DE LA APLICACIN EN PANEL DE CONTROL ODBC

import java.sql.*;
public class accessApp {
public static void main(String[] args) {
try {
System.out.println("\nJDBC Access");
System.out.println("===========");
// cadena de conexion con la ruta fisica a la BD
String db = "empresas.mdb";
// esta ruta puede escribirse "c:\\empresas.mdb" o "c:\\..Carp..\\empresas.mdb"
String url = "jdbc:odbc:MS Access Database;DBQ=" + db;
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("\nEstableciendo conexion...");
Connection con = DriverManager.getConnection (url, "", "");
System.out.println("\nConexion establecida con: \"" + db + "\".");
System.out.println("");
Statement select = con.createStatement();
ResultSet nombres = select.executeQuery("SELECT TOP 8 * FROM Tabla1 ORDER BY Id");
System.out.println("Mostrar los 8 primeros registros:");
System.out.println("");
System.out.println("\tNOMBRE");
System.out.println("");
int col = nombres.findColumn ("Nombre");
boolean seguir = nombres.next();
while (seguir) {
System.out.println ("\t" + nombres.getString(col));
seguir = nombres.next(); }
System.out.println("");
// liberar recursos
nombres.close();
select.close();
DatabaseMetaData dm = null;
ResultSet rs = null;
dm = con.getMetaData();
rs = dm.getCatalogs();
System.out.println("Informacion sobre el Driver:\n");
System.out.println("\tDriver Name: "+ dm.getDriverName());
System.out.println("\tDriver Version: "+ dm.getDriverVersion ());
System.out.println("\nInformacion sobre el servidor de BD:\n");
System.out.println("\tDatabase Name: "+ dm.getDatabaseProductName());
System.out.println("\tDatabase Version: "+ dm.getDatabaseProductVersion());
System.out.println("\nBases de datos en esta carpeta:\n");
int n = 1;
while(rs.next()){
System.out.println("\t" + n + " - " + rs.getString(1));
n+=1; }
// liberar recursos
rs.close();
con.close();
System.out.println("\nConexion con: \"" + db + "\" cerrada.\n\n"); }
catch (Exception dato)
{
System.out.println("\nError al realizar alguna accion del programa.\n\n");
}
}
}
NOTA: RECLAME LA BASE DE DATOS empresas.mdb AL PROFESOR
ESTRUCTURA: Tabla1: Id Nombre Telefono

import java.awt.*;
import java.sql.*;
import java.awt.event.*;
class DatosPersonales extends Frame
implements ActionListener
{ Button crear, ver, insertar, cerrar;
TextField informacion;
Panel principal;
Connection conexion;
DatosPersonales()
{ super("Datos personales");
setLocation(100,100);
setSize(400,300);
principal=new Panel();
crear=new Button ("Crear");
crear.addActionListener(this);
ver=new Button ("Ver");
ver.addActionListener(this);
insertar=new Button("Insertar");
insertar.addActionListener(this);
cerrar=new Button("Cerrar");
cerrar.addActionListener(this);
informacion=new TextField(20);
principal.add(informacion);
principal.add(crear);
principal.add(insertar);
principal.add(ver);
principal.add(cerrar);
addWindowListener(new Cerrar());
principal.setBackground(SystemColor.control);
add(principal);
setVisible(true);
try
{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");}
catch(ClassNotFoundException e)
{ informacion.setText("No se pudo cargar el controlador JDBC-ODBC");}
}
private void Crear_tabla()
{ Statement sentencia;
try
{
conexion=DriverManager.getConnection("jdbc:odbc:Personal");
sentencia=conexion.createStatement();
try
{
sentencia.executeUpdate("DROP TABLE DATOSPERSONALES");
}
catch(SQLException e){informacion.setText("Error al crear la tabla");
System.out.println(e);}
sentencia.executeUpdate("CREATE TABLE DATOSPERSONALES("+
"NOMBRE CHAR(20) NOT NULL,"+
"APELLIDOS CHAR(20),"+
"EDAD CHAR(3),"+
"TELEFONO CHAR(10))");
informacion.setText("Tabla creada");
conexion.close();
}
catch(SQLException e){}
}
public void actionPerformed(ActionEvent e)

{ String com=e.getActionCommand();
if ("Crear".equals(com))
{ informacion.setText("");
Crear_tabla();}
else
if ("Insertar".equals(com))
{ new Insertar(this);
}
else
if ("Ver".equals(com))
{
new Ver(this);
}
else
{dispose();System.exit(0);}
}
class Cerrar extends WindowAdapter
{ public void windowClosing(WindowEvent e)
{ dispose();
System.exit(0);
}
}
public static void main(String args[])
{ new DatosPersonales();}
}
class Insertar extends Dialog implements ActionListener
{
private Connection conexion;
private Button incluir,terminar;
private TextField nombre,apellidos,edad,telefono;
Insertar(Frame f)
{ super(f,"Insertar datos",true);
setSize(400,300);
nombre=new TextField(20);
apellidos=new TextField(20);
edad=new TextField(3);
telefono=new TextField(10);
incluir=new Button("Incluir");
incluir.addActionListener(this);
terminar=new Button("Terminar");
terminar.addActionListener(this);
Panel P_Datos=new Panel();
P_Datos.add(new Label("Nombre : "));
P_Datos.add(nombre);
P_Datos.add(new Label("Apellidos: "));
P_Datos.add(apellidos);
P_Datos.add(new Label("Edad : "));
P_Datos.add(edad);
P_Datos.add(new Label("Telefono : "));
P_Datos.add(telefono);
P_Datos.add(incluir);
P_Datos.add(terminar);
nombre.setEditable(true);
apellidos.setEditable(true);
edad.setEditable(true);
telefono.setEditable(true);
add(P_Datos);
setVisible(true);
}
private void insertar_fila()

{ Statement sentencia;
try{
conexion=DriverManager.getConnection("jdbc:odbc:Personal");
sentencia=conexion.createStatement();
sentencia.executeUpdate("INSERT INTO DATOSPERSONALES"+
" VALUES ('"+nombre.getText()+"',"+
"'"+apellidos.getText()+"',"+
"'"+edad.getText()+"',"+
"'"+telefono.getText()+"')");
}
catch(SQLException e){}
}
public void actionPerformed(ActionEvent e)
{ String com=e.getActionCommand();
if ("Incluir".equals(com))
{insertar_fila();
nombre.setText("");
apellidos.setText("");
edad.setText("");
telefono.setText("");
}
else
{
if(conexion!=null)
{
try
{
conexion.close();
}
catch(SQLException ex){}
}
dispose();
}
}
}
class Ver extends Dialog
implements ActionListener
{
private Connection conexion;
private ResultSet resultado;
private Button siguiente,terminar;
private TextField nombre,apellidos, edad,telefono;
Ver(Frame f)
{
super(f,"Ver datos",true);
setSize(400,300);
nombre=new TextField(20);
apellidos=new TextField(20);
edad=new TextField(3);
telefono=new TextField(10);
siguiente=new Button("Siguiente");
siguiente.addActionListener(this);
terminar=new Button("Terminar");
terminar.addActionListener(this);
Panel P_Datos=new Panel();
P_Datos.add(new Label("Nombre : "));
P_Datos.add(nombre);
P_Datos.add(new Label("Apellidos: "));
P_Datos.add(apellidos);
P_Datos.add(new Label("Edad : "));

P_Datos.add(edad);
P_Datos.add(new Label("Telefono : "));
P_Datos.add(telefono);
P_Datos.add(siguiente);
P_Datos.add(terminar);
add(P_Datos);
nombre.setEditable(false);
apellidos.setEditable(false);
edad.setEditable(false);
telefono.setEditable(false);
mostrar();
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{ String com=e.getActionCommand();
if ("Siguiente".equals(com))
siguiente();
else
{
if (conexion!=null)
{
try
{
conexion.close();
}
catch(SQLException ex){}
}
dispose();
}
}
private void mostrar()
{
Statement sentencia;
try{
conexion=DriverManager.getConnection("jdbc:odbc:Personal");
sentencia=conexion.createStatement();
resultado=sentencia.executeQuery("SELECT * FROM DATOSPERSONALES");
siguiente();
}
catch(SQLException e){}
}
private void ver_Datos()
{ try
{
nombre.setText(resultado.getString("NOMBRE"));
apellidos.setText(resultado.getString("APELLIDOS"));
edad.setText(resultado.getString("EDAD"));
telefono.setText(resultado.getString("TELEFONO"));
}
catch (SQLException e){}
}
private void siguiente()
{ try
{
if (resultado.next()) ver_Datos();
}
catch(SQLException e){}
catch(Exception ex){}
}
}

MANEJO DE EXCEPCIONES EN LA CLASE LIBRE


import java.io.*;
class ValorExcepcion extends Exception{
ValorExcepcion(){super("Valor Negativo");}
public static void siNegativo (int Valor)throws ValorExcepcion{
if (Valor<0){ throw new ValorExcepcion();}}
public static void siNegativo (double Valor) throws ValorExcepcion{
if (Valor<0){throw new ValorExcepcion();}}
}
public class libre{
static void imp (String men){System.out.print(men);}
static String leerCadena(){
String dato="";
InputStreamReader f=new InputStreamReader (System.in);
BufferedReader tec=new BufferedReader(f);
try{dato=tec.readLine();}
catch (IOException e){}
return dato;}
static int leerEntero(){
int datoEnt=0;
String dato=leerCadena();
try{ datoEnt=Integer.parseInt (dato);
ValorExcepcion.siNegativo(datoEnt);}
catch(ValorExcepcion e){imp ("ERROR...." + e.getMessage());
return leerEntero();}
catch (NumberFormatException e){
imp ("ERROR...."+ e.getMessage()+"No es un numero");
return leerEntero();}
return datoEnt;}
static double leerReal(){
double datoReal=0;
String dato=leerCadena();
try{ datoReal=Double.parseDouble (dato);
ValorExcepcion.siNegativo(datoReal);}
catch (ValorExcepcion e){
imp ("ERROR..." + e.getMessage() + "No es un numero");
return leerReal();}
return datoReal;}
public static void main (String [] a){
imp ("\n\n PROGRAMA DE VENTA DE ARTICULOS PARA EL HOGAR \n\n");
imp ("Digite su nombre: "); double total=0;
String nom=leerCadena();
imp ("Ingrese el numero de articulos que desea llevar: ");
int articulos=leerEntero();
for (int k=1; k<=articulos; k++){
imp ("Digite la cantidad del articulo"+k );
int cant=leerEntero ();
imp("Digite el valor del articulo"+k );
double precio=leerReal();
total=total+cant*precio;}
imp ("\n\n El total a pagar por los articulos es: "+total+"\n\n");
}
}

También podría gustarte