Java

Hola... Estoy haciendo un programa en Java con conexión a bd Access, pero también necesito conectarlo a Oracle, éste tiene que adicionar, modificar, borrar, consultar y borrar y no me funciona el borrado y no sé hacer modificación... Me puedes ayudar? Estoy ejecutándolo con RealJ...Adjunto el programa... Pero puede ser cualquier programa con las condiciones descritas... Mil gracias!!
import java.awt.*;
import java.sql.*;
import java.awt.event.*;
class Prueba extends Frame
implements ActionListener
{ Button crear, consultar, insertar, borrar, cerrar;
TextField informacion;
Panel principal;
Connection conexion;
//MENU PRINCIPAL
Prueba()
{ super("Ventas");
setSize(200,120);
principal=new Panel();
crear=new Button ("Crear");
crear.addActionListener(this);
consultar=new Button ("Consultar");
consultar.addActionListener(this);
insertar=new Button("Insertar");
insertar.addActionListener(this);
borrar=new Button("Borrar");
borrar.addActionListener(this);
cerrar=new Button("Cerrar");
cerrar.addActionListener(this);
informacion=new TextField(20);
principal.add(informacion);
principal.add(crear);
principal.add(insertar);
principal.add(borrar);
principal.add(consultar);
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:Ventas");
sentencia=conexion.createStatement();
try
{
sentencia.executeUpdate("DROP TABLE Factura");
}
catch(SQLException e){informacion.setText("Error al crear la tabla");
System.out.println(e);}
sentencia.executeUpdate("CREATE TABLE Factura("+
"num_factura CHAR(20) NOT NULL,"+
"cod_vendedor CHAR(20),"+
"id_cliente CHAR(20),"+
"fecha CHAR(20))");
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 ("Borrar".equals(com))
{ new Borrar(this);
}
else
if ("Consultar".equals(com))
{
new Consultar(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 Prueba();}
}
class Insertar extends Dialog implements ActionListener
{
private Connection conexion;
private Button incluir,terminar;
private TextField num_factura, cod_vendedor,id_cliente,fecha;
Insertar(Frame f)
{ super(f,"Insertar datos",true);
setSize(320,180);
num_factura=new TextField(20);
cod_vendedor=new TextField(20);
id_cliente=new TextField(20);
fecha=new TextField(20);
incluir=new Button("Incluir");
incluir.addActionListener(this);
terminar=new Button("Terminar");
terminar.addActionListener(this);
Panel P_Fact=new Panel();
P_Fact.add(new Label("Número Factura : "));
P_Fact.add(num_factura);
P_Fact.add(new Label("Codigo Vendedor : "));
P_Fact.add(cod_vendedor);
P_Fact.add(new Label("Codigo Cliente : "));
P_Fact.add(id_cliente);
P_Fact.add(new Label("Fecha : "));
P_Fact.add(fecha);
P_Fact.add(incluir);
P_Fact.add(terminar);
num_factura.setEditable(true);
cod_vendedor.setEditable(true);
id_cliente.setEditable(true);
fecha.setEditable(true);
add(P_Fact);
setVisible(true);
}
private void insertar_fila()
{ Statement sentencia;
try{
conexion=DriverManager.getConnection("jdbc:odbc:Ventas");
sentencia=conexion.createStatement();
sentencia.executeUpdate("INSERT INTO Factura"+
" VALUES ('"+num_factura.getText()+"',"+
"'"+cod_vendedor.getText()+"',"+
"'"+id_cliente.getText()+"',"+
"'"+fecha.getText()+"')");
}
catch(SQLException e){}
}
public void actionPerformed(ActionEvent e)
{ String com=e.getActionCommand();
if ("Incluir".equals(com))
{insertar_fila();
num_factura.setText("");
cod_vendedor.setText("");
id_cliente.setText("");
fecha.setText("");
}
else
{
if(conexion!=null)
{
try
{
conexion.close();
}
catch(SQLException ex){}
}
dispose();
}
}
}
class Consultar extends Dialog
implements ActionListener
{
private Connection conexion;
private ResultSet resultado;
private Button siguiente, terminar;
private TextField num_factura,cod_vendedor,id_cliente, fecha;
Consultar(Frame f)
{
super(f,"Consultar datos",true);
setSize(320,180);
num_factura=new TextField(20);
cod_vendedor=new TextField(20);
id_cliente=new TextField(20);
fecha=new TextField(20);
siguiente=new Button("Siguiente");
siguiente.addActionListener(this);
terminar=new Button("Terminar");
terminar.addActionListener(this);
Panel P_Datos=new Panel();
P_Datos.add(new Label("Numero Factura : "));
P_Datos.add(num_factura);
P_Datos.add(new Label("Código Vendedor : "));
P_Datos.add(cod_vendedor);
P_Datos.add(new Label("Cliente : "));
P_Datos.add(id_cliente);
P_Datos.add(new Label("Fecha : "));
P_Datos.add(fecha);
P_Datos.add(siguiente);
P_Datos.add(terminar);
add(P_Datos);
num_factura.setEditable(false);
cod_vendedor.setEditable(false);
id_cliente.setEditable(false);
fecha.setEditable(false);
mostrar();
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{ String com=e.getActionCommand();
if ("Siguiente".equals(com))
siguiente();
else
{
if...

6 Respuestas

Respuesta
1
Bien, para borrar, lo primeo que haria es habilitar la navegación por registros, de la misma forma que hay en consultar, con el método "mostrar()".
En segundo lugar controlar el evento de pulsar el botón borrar.
Por último, como la tabla que has creado no tiene claves únicas, la sentencia para borrar sería:
DELETE FROM table WHERE campo1 = valor1 AND campo2 = valor2 ...
sentencia.executeUpdate("delete from Factura where"+
" num_factura = '"+num_factura.getText()+"' "+
"and cod_vendedor = '"+cod_vendedor.getText()+"' "+
"and id_cliente = '"+id_cliente.getText()+"' "+
"and fecha = '"+fecha.getText()+"'");
Para realizar una modificación la sentencia es:
UPDATE tabla SET campo1 = valor1, campo2 = valor2, .... WHERE campoA = valorA AND campoB = valorB ...
Creo que son pistas suficientes para realizar lo que deseas, sin embargo, si no te funciona, dímelo y te envío el código.
Hola muchas gracias por la respuesta... pues te cuento que ya hice algunas modificaciones que me dijiste excepto lo de modificar (no entiendo bien) no salen errores pero sale el mensaje "java.lang.NoClassDefFoundError: prueba (wrong name: Prueba)
at java.lang.ClassLoader.defineClass0(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:509)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:246)
at java.net.URLClassLoader.access$100(URLClassLoader.java:54)
at java.net.URLClassLoader$1.run(URLClassLoader.java:193)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:186)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:265)
at java.lang.ClassLoader.loadClass(ClassLoader.java:262)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:322)
Exception in thread "main" Exit code: 1
There were errors" y no corre!!!
TE AGRADECERIA MUCHISIMO SI ME PUEDES CORREGIR EL CODIGO... llevo una semana con lo mismo y estoy aburridísima... Auxilio! Yo ejecuto el prog. en RealJ
import java.awt.*;
import java.sql.*;
import java.awt.event.*;
class Prueba extends Frame
implements ActionListener
{ Button crear, consultar, insertar, borrar, cerrar;
TextField informacion;
Panel principal;
Connection conexion;
//MENU PRINCIPAL
Prueba()
{ super("Ventas");
setSize(200,120);
principal=new Panel();
crear=new Button ("Crear");
crear.addActionListener(this);
consultar=new Button ("Consultar");
consultar.addActionListener(this);
insertar=new Button("Insertar");
insertar.addActionListener(this);
borrar=new Button("Borrar");
borrar.addActionListener(this);
cerrar=new Button("Cerrar");
cerrar.addActionListener(this);
informacion=new TextField(20);
principal.add(informacion);
principal.add(crear);
principal.add(insertar);
principal.add(borrar);
principal.add(consultar);
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:Ventas");
sentencia=conexion.createStatement();
try
{
sentencia.executeUpdate("DROP TABLE Factura");
}
catch(SQLException e){informacion.setText("Error al crear la tabla");
System.out.println(e);}
sentencia.executeUpdate("CREATE TABLE Factura("+
"num_factura CHAR(20) NOT NULL,"+
"cod_vendedor CHAR(20),"+
"id_cliente CHAR(20),"+
"fecha CHAR(20))");
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 ("Borrar".equals(com))
{ new Borrar(this);
}
else
if ("Consultar".equals(com))
{
new Consultar(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 Prueba();}
}
class Insertar extends Dialog implements ActionListener
{
private Connection conexion;
private Button incluir,terminar;
private TextField num_factura, cod_vendedor,id_cliente,fecha;
Insertar(Frame f)
{ super(f,"Insertar datos",true);
setSize(320,180);
num_factura=new TextField(20);
cod_vendedor=new TextField(20);
id_cliente=new TextField(20);
fecha=new TextField(20);
incluir=new Button("Incluir");
incluir.addActionListener(this);
terminar=new Button("Terminar");
terminar.addActionListener(this);
Panel P_Fact=new Panel();
P_Fact.add(new Label("Número Factura : "));
P_Fact.add(num_factura);
P_Fact.add(new Label("Codigo Vendedor : "));
P_Fact.add(cod_vendedor);
P_Fact.add(new Label("Codigo Cliente : "));
P_Fact.add(id_cliente);
P_Fact.add(new Label("Fecha : "));
P_Fact.add(fecha);
P_Fact.add(incluir);
P_Fact.add(terminar);
num_factura.setEditable(true);
cod_vendedor.setEditable(true);
id_cliente.setEditable(true);
fecha.setEditable(true);
add(P_Fact);
setVisible(true);
}
private void insertar_fila()
{ Statement sentencia;
try{
conexion=DriverManager.getConnection("jdbc:odbc:Ventas");
sentencia=conexion.createStatement();
sentencia.executeUpdate("INSERT INTO Factura"+
" VALUES ('"+num_factura.getText()+"',"+
"'"+cod_vendedor.getText()+"',"+
"'"+id_cliente.getText()+"',"+
"'"+fecha.getText()+"')");
}
catch(SQLException e){}
}
public void actionPerformed(ActionEvent e)
{ String com=e.getActionCommand();
if ("Incluir".equals(com))
{insertar_fila();
num_factura.setText("");
cod_vendedor.setText("");
id_cliente.setText("");
fecha.setText("");
}
else
{
if(conexion!=null)
{
try
{
conexion.close();
}
catch(SQLException ex){}
}
dispose();
}
}
}
class Consultar extends Dialog
implements ActionListener
{
private Connection conexion;
private ResultSet resultado;
private Button siguiente, terminar;
private TextField num_factura,cod_vendedor,id_cliente, fecha;
Consultar(Frame f)
{
super(f,"Consultar datos",true);
setSize(320,180);
num_factura=new TextField(20);
cod_vendedor=new TextField(20);
id_cliente=new TextField(20);
fecha=new TextField(20);
siguiente=new Button("Siguiente");
siguiente.addActionListener(this);
terminar=new Button("Terminar");
terminar.addActionListener(this);
Panel P_Datos=new Panel();
P_Datos.add(new Label("Numero Factura : "));
P_Datos.add(num_factura);
P_Datos.add(new Label("Código Vendedor : "));
P_Datos.add(cod_vendedor);
P_Datos.add(new Label("Cliente : "));
P_Datos.add(id_cliente);
P_Datos.add(new Label("Fecha : "));
P_Datos.add(fecha);
P_Datos.add(siguiente);
P_Datos.add(terminar);
add(P_Datos);
num_factura.setEditable(false);
cod_vendedor.setEditable(false);
id_cliente.setEditable(false);
fecha.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:Ventas");
sentencia=conexion.createStatement();
resultado=sentencia.executeQuery("SELECT * FROM Factura");
siguiente();
}
catch(SQLException e){}
}
private void consultar_Datos()
{ try
{
num_factura.setText(resultado.getString("num_factura"));
cod_vendedor.setText(resultado.getString("cod_vendedor"));
id_cliente.setText(resultado.getString("id_cliente"));
fecha.setText(resultado.getString("fecha"));
}
catch (SQLException e){}
}
private void siguiente()
{ try
{
if (resultado.next()) consultar_Datos();
}
catch(SQLException e){}
catch(Exception ex){}
}
class Borrar extends Dialog implements ActionListener
{
private Connection conexion;
private ResultSet resultado;
private Button borrar,siguiente,terminar;
private TextField num_factura, cod_vendedor,id_cliente,fecha;
Borrar(Frame f)
{ super(f,"Borrar datos",true);
setSize(320,180);
num_factura=new TextField(20);
cod_vendedor=new TextField(20);
id_cliente=new TextField(20);
fecha=new TextField(20);
borrar=new Button("Borrar");
borrar.addActionListener(this);
siguiente=new Button("Siguiente");
siguiente.addActionListener(this);
terminar=new Button("Terminar");
terminar.addActionListener(this);
Panel P_Fact=new Panel();
P_Fact.add(new Label("Número Factura : "));
P_Fact.add(num_factura);
P_Fact.add(new Label("Codigo Vendedor : "));
P_Fact.add(cod_vendedor);
P_Fact.add(new Label("Codigo Cliente : "));
P_Fact.add(id_cliente);
P_Fact.add(new Label("Fecha : "));
P_Fact.add(fecha);
P_Fact.add(borrar);
P_Fact.add(siguiente);
P_Fact.add(terminar);
add(P_Fact);
num_factura.setEditable(false);
cod_vendedor.setEditable(false);
id_cliente.setEditable(false);
fecha.setEditable(false);
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 borrar_registro()
{ Statement sentencia;
try{
conexion=DriverManager.getConnection("jdbc:odbc:Ventas");
sentencia=conexion.createStatement();
sentencia.executeUpdate("delete from Factura where"+
" num_factura = '"+num_factura.getText()+"' "+
"and cod_vendedor = '"+cod_vendedor.getText()+"' "+
"and id_cliente = '"+id_cliente.getText()+"' "+
"and fecha = '"+fecha.getText()+"'");
siguiente();
}
catch(SQLException e){}
}
private void consultar_Datos()
{ try
{
num_factura.setText(resultado.getString("num_factura"));
cod_vendedor.setText(resultado.getString("cod_vendedor"));
id_cliente.setText(resultado.getString("id_cliente"));
fecha.setText(resultado.getString("fecha"));
}
catch (SQLException e){}
}
private void siguiente()
{ try
{
if (resultado.next()) consultar_Datos();
}
catch(SQLException e){}
catch(Exception ex){}
}
}
}
Bien, pues hay te va el código con la modificación y no dudes en preguntarme lo que quieras:
import java.awt.*;
import java.sql.*;
import java.awt.event.*;
class Prueba extends Frame
implements ActionListener {
Button crear, consultar, insertar, borrar, modificar, cerrar;
TextField informacion;
Panel principal;
Connection conexion;
//MENU PRINCIPAL
Prueba() {
super("Ventas");
setSize(200,120);
principal=new Panel();
crear=new Button("Crear");
crear.addActionListener(this);
consultar=new Button("Consultar");
consultar.addActionListener(this);
insertar=new Button("Insertar");
insertar.addActionListener(this);
borrar=new Button("Borrar");
borrar.addActionListener(this);
modificar=new Button("Modificar");
modificar.addActionListener(this);
cerrar=new Button("Cerrar");
cerrar.addActionListener(this);
informacion=new TextField(20);
principal.add(informacion);
principal.add(crear);
principal.add(insertar);
principal.add(borrar);
principal.add(modificar);
principal.add(consultar);
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:Ventas");
sentencia=conexion.createStatement();
try {
sentencia.executeUpdate("DROP TABLE Factura");
} catch(SQLException e){informacion.setText("Error al crear la tabla");
System.out.println(e);}
sentencia.executeUpdate("CREATE TABLE Factura("+
"num_factura CHAR(20) NOT NULL,"+
"cod_vendedor CHAR(20),"+
"id_cliente CHAR(20),"+
"fecha CHAR(20))");
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 ("Borrar".equals(com)) {
new Borrar(this);
} else if ("Modificar".equals(com)) {
new Modificar(this);
} else if ("Consultar".equals(com)) {
new Consultar(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 Prueba();}
class Insertar extends Dialog implements ActionListener {
private Connection conexion;
private Button incluir,terminar;
private TextField num_factura, cod_vendedor,id_cliente,fecha;
Insertar(Frame f) {
super(f,"Insertar datos",true);
setSize(320,180);
num_factura=new TextField(20);
cod_vendedor=new TextField(20);
id_cliente=new TextField(20);
fecha=new TextField(20);
incluir=new Button("Incluir");
incluir.addActionListener(this);
terminar=new Button("Terminar");
terminar.addActionListener(this);
Panel P_Fact=new Panel();
P_Fact.add(new Label("Número Factura : "));
P_Fact.add(num_factura);
P_Fact.add(new Label("Codigo Vendedor : "));
P_Fact.add(cod_vendedor);
P_Fact.add(new Label("Codigo Cliente : "));
P_Fact.add(id_cliente);
P_Fact.add(new Label("Fecha : "));
P_Fact.add(fecha);
P_Fact.add(incluir);
P_Fact.add(terminar);
num_factura.setEditable(true);
cod_vendedor.setEditable(true);
id_cliente.setEditable(true);
fecha.setEditable(true);
add(P_Fact);
setVisible(true);
}
private void insertar_fila() {
Statement sentencia;
try{
conexion=DriverManager.getConnection("jdbc:odbc:Ventas");
sentencia=conexion.createStatement();
sentencia.executeUpdate("INSERT INTO Factura"+
" VALUES ('"+num_factura.getText()+"',"+
"'"+cod_vendedor.getText()+"',"+
"'"+id_cliente.getText()+"',"+
"'"+fecha.getText()+"')");
} catch(SQLException e){}
}
public void actionPerformed(ActionEvent e) {
String com=e.getActionCommand();
if ("Incluir".equals(com)) {
insertar_fila();
num_factura.setText("");
cod_vendedor.setText("");
id_cliente.setText("");
fecha.setText("");
} else {
if(conexion!=null) {
try {
conexion.close();
} catch(SQLException ex){}
}
dispose();
}
}
}
class Consultar extends Dialog
implements ActionListener {
private Connection conexion;
private ResultSet resultado;
private Button siguiente, terminar;
private TextField num_factura,cod_vendedor,id_cliente, fecha;
Consultar(Frame f) {
super(f,"Consultar datos",true);
setSize(320,180);
num_factura=new TextField(20);
cod_vendedor=new TextField(20);
id_cliente=new TextField(20);
fecha=new TextField(20);
siguiente=new Button("Siguiente");
siguiente.addActionListener(this);
terminar=new Button("Terminar");
terminar.addActionListener(this);
Panel P_Datos=new Panel();
P_Datos.add(new Label("Numero Factura : "));
P_Datos.add(num_factura);
P_Datos.add(new Label("Código Vendedor : "));
P_Datos.add(cod_vendedor);
P_Datos.add(new Label("Cliente : "));
P_Datos.add(id_cliente);
P_Datos.add(new Label("Fecha : "));
P_Datos.add(fecha);
P_Datos.add(siguiente);
P_Datos.add(terminar);
add(P_Datos);
num_factura.setEditable(false);
cod_vendedor.setEditable(false);
id_cliente.setEditable(false);
fecha.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:Ventas");
sentencia=conexion.createStatement();
resultado=sentencia.executeQuery("SELECT * FROM Factura");
siguiente();
} catch(SQLException e){}
}
private void consultar_Datos() {
try {
num_factura.setText(resultado.getString("num_factura"));
cod_vendedor.setText(resultado.getString("cod_vendedor"));
id_cliente.setText(resultado.getString("id_cliente"));
fecha.setText(resultado.getString("fecha"));
} catch (SQLException e){}
}
private void siguiente() {
try {
if (resultado.next()) consultar_Datos();
} catch(SQLException e){} catch(Exception ex){}
}
}
class Borrar extends Dialog implements ActionListener {
private Connection conexion;
private ResultSet resultado;
private Button borrar,siguiente,terminar;
private TextField num_factura, cod_vendedor,id_cliente,fecha;
Borrar(Frame f) {
super(f,"Borrar datos",true);
setSize(320,180);
num_factura=new TextField(20);
cod_vendedor=new TextField(20);
id_cliente=new TextField(20);
fecha=new TextField(20);
borrar=new Button("Borrar");
borrar.addActionListener(this);
siguiente=new Button("Siguiente");
siguiente.addActionListener(this);
terminar=new Button("Terminar");
terminar.addActionListener(this);
Panel P_Fact=new Panel();
P_Fact.add(new Label("Número Factura : "));
P_Fact.add(num_factura);
P_Fact.add(new Label("Codigo Vendedor : "));
P_Fact.add(cod_vendedor);
P_Fact.add(new Label("Codigo Cliente : "));
P_Fact.add(id_cliente);
P_Fact.add(new Label("Fecha : "));
P_Fact.add(fecha);
P_Fact.add(borrar);
P_Fact.add(siguiente);
P_Fact.add(terminar);
add(P_Fact);
num_factura.setEditable(false);
cod_vendedor.setEditable(false);
id_cliente.setEditable(false);
fecha.setEditable(false);
mostrar();
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String com=e.getActionCommand();
if ("Siguiente".equals(com))
siguiente();
else if ("Borrar".equals(com))
borrar_registro();
else {
if (conexion!=null) {
try {
conexion.close();
} catch(SQLException ex){}
}
dispose();
}
}
private void mostrar() {
Statement sentencia;
try{
conexion=DriverManager.getConnection("jdbc:odbc:Ventas");
sentencia=conexion.createStatement();
resultado=sentencia.executeQuery("SELECT * FROM Factura");
siguiente();
} catch(SQLException e){}
}
private void borrar_registro() {
Statement sentencia;
try{
conexion=DriverManager.getConnection("jdbc:odbc:Ventas");
sentencia=conexion.createStatement();
sentencia.executeUpdate("delete from Factura where"+
" num_factura = '"+num_factura.getText()+"' "+
"and cod_vendedor = '"+cod_vendedor.getText()+"' "+
"and id_cliente = '"+id_cliente.getText()+"' "+
"and fecha = '"+fecha.getText()+"'");
siguiente();
} catch(SQLException e){e.printStackTrace();}
}
private void consultar_Datos() {
try {
num_factura.setText(resultado.getString("num_factura"));
cod_vendedor.setText(resultado.getString("cod_vendedor"));
id_cliente.setText(resultado.getString("id_cliente"));
fecha.setText(resultado.getString("fecha"));
} catch (SQLException e){}
}
private void siguiente() {
try {
if (resultado.next()) consultar_Datos();
} catch(SQLException e){} catch(Exception ex){}
}
}
class Modificar extends Dialog implements ActionListener {
private Connection conexion;
private ResultSet resultado;
private Button modificar,siguiente,terminar;
private TextField num_factura, cod_vendedor,id_cliente,fecha;
private String tmpNumFactura, tmpCodVendedor, tmpIdCliente, tmpFecha;
Modificar(Frame f) {
super(f,"Modificar datos",true);
setSize(320,180);
num_factura=new TextField(20);
cod_vendedor=new TextField(20);
id_cliente=new TextField(20);
fecha=new TextField(20);
modificar=new Button("Modificar");
modificar.addActionListener(this);
siguiente=new Button("Siguiente");
siguiente.addActionListener(this);
terminar=new Button("Terminar");
terminar.addActionListener(this);
Panel P_Fact=new Panel();
P_Fact.add(new Label("Número Factura : "));
P_Fact.add(num_factura);
P_Fact.add(new Label("Codigo Vendedor : "));
P_Fact.add(cod_vendedor);
P_Fact.add(new Label("Codigo Cliente : "));
P_Fact.add(id_cliente);
P_Fact.add(new Label("Fecha : "));
P_Fact.add(fecha);
P_Fact.add(modificar);
P_Fact.add(siguiente);
P_Fact.add(terminar);
add(P_Fact);
mostrar();
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String com=e.getActionCommand();
if ("Siguiente".equals(com))
siguiente();
else if ("Modificar".equals(com))
modificar_registro();
else {
if (conexion!=null) {
try {
conexion.close();
} catch(SQLException ex){}
}
dispose();
}
}
private void mostrar() {
Statement sentencia;
try{
conexion=DriverManager.getConnection("jdbc:odbc:Ventas");
sentencia=conexion.createStatement();
resultado=sentencia.executeQuery("SELECT * FROM Factura");
siguiente();
} catch(SQLException e){}
}
private void modificar_registro() {
Statement sentencia;
try{
conexion=DriverManager.getConnection("jdbc:odbc:Ventas");
sentencia=conexion.createStatement();
String ejecucion = "update Factura set "+
" num_factura = '"+num_factura.getText()+"', "+
"cod_vendedor = '"+cod_vendedor.getText()+"', "+
"id_cliente = '"+id_cliente.getText()+"', "+
"fecha = '"+fecha.getText()+"' " +
" where " +
" num_factura = '"+tmpNumFactura+"' "+
"and cod_vendedor = '"+tmpCodVendedor+"' "+
"and id_cliente = '"+tmpIdCliente+"' "+
"and fecha = '"+tmpFecha+"'";
sentencia.executeUpdate(ejecucion);
} catch(SQLException e){e.printStackTrace();}
}
private void consultar_Datos() {
try {
tmpNumFactura = resultado.getString("num_factura");
tmpCodVendedor = resultado.getString("cod_vendedor");
tmpIdCliente = resultado.getString("id_cliente");
tmpFecha = resultado.getString("fecha");
num_factura.setText(tmpNumFactura);
cod_vendedor.setText(tmpCodVendedor);
id_cliente.setText(tmpIdCliente);
fecha.setText(tmpFecha);
} catch (SQLException e){}
}
private void siguiente() {
try {
if (resultado.next()) consultar_Datos();
} catch(SQLException e){} catch(Exception ex){}
}
}
}
Respuesta
1
Pues aqui tienes, el código para que te funciones todo con Oracle. Lo único que tienes que cambiar es la Ip, el puerto, el nombre de base de datos, usuario y password donde encuentres
(Connection)DriverManager.getConnection("jdbc:oracle:thin:@IP:PUERTO:NOMBREDB","USUARIO","PASSWORD");
//Clase Prueba
import java.awt.*;
import java.sql.*;
import java.awt.event.*;
class Prueba extends Frame
implements ActionListener
{ Button crear, consultar, insertar, borrar, actualizar, cerrar;
TextField informacion;
Panel principal;
Connection conexion;
//MENU PRINCIPAL
Prueba()
{ super("Ventas");
setSize(220,120);
principal=new Panel();
crear=new Button ("Crear");
crear.addActionListener(this);
consultar=new Button ("Consultar");
consultar.addActionListener(this);
insertar=new Button("Insertar");
insertar.addActionListener(this);
borrar=new Button("Borrar");
borrar.addActionListener(this);
actualizar = new Button("Actualizar");
actualizar.addActionListener(this);
cerrar=new Button("Cerrar");
cerrar.addActionListener(this);
informacion=new TextField(20);
principal.add(informacion);
principal.add(crear);
principal.add(insertar);
principal.add(borrar);
principal.add(consultar);
principal.add(actualizar);
principal.add(cerrar);
addWindowListener(new Cerrar());
principal.setBackground(SystemColor.control);
add(principal);
setVisible(true);
try
{
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
}
catch(Exception e)
{
System.out.println(e);
informacion.setText("No se pudo cargar el controlador JDBC-ODBC");}
}
private void Crear_tabla()
{ Statement sentencia;
try
{
conexion = (Connection)DriverManager.getConnection("jdbc:oracle:thin:@192.168.2.10:1521:PRFNMT","DGT","DGT");
sentencia=conexion.createStatement();
try
{
sentencia.executeUpdate("DROP TABLE Factura");
}
catch(SQLException e){informacion.setText("Error al crear la tabla");
System.out.println(e);}
sentencia.executeUpdate("create table FACTURA"+
"("+
"NUM_FACTURA VARCHAR2(20),"+
"COD_VENDEDOR VARCHAR2(20),"+
"ID_CLIENTE VARCHAR2(20),"+
"FECHA VARCHAR2(20)"+
")");
informacion.setText("Tabla creada");
sentencia.close();
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 ("Borrar".equals(com))
{ new Borrar(this);
}
else
if ("Consultar".equals(com))
{
new Consultar(this);
}
else{
if ("Actualizar".equals(com))
{
new Actualizar(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 Prueba();}
}
//Clase insertar
import java.awt.*;
import java.sql.*;
import java.awt.event.*;
class Insertar extends Dialog implements ActionListener
{
private Connection conexion;
private Statement sentencia;
private Button incluir,terminar;
private TextField num_factura, cod_vendedor,id_cliente,fecha;
Insertar(Frame f)
{ super(f,"Insertar datos",true);
setSize(320,180);
num_factura=new TextField(20);
cod_vendedor=new TextField(20);
id_cliente=new TextField(20);
fecha=new TextField(20);
incluir=new Button("Incluir");
incluir.addActionListener(this);
terminar=new Button("Terminar");
terminar.addActionListener(this);
Panel P_Fact=new Panel();
P_Fact.add(new Label("Número Factura : "));
P_Fact.add(num_factura);
P_Fact.add(new Label("Codigo Vendedor : "));
P_Fact.add(cod_vendedor);
P_Fact.add(new Label("Codigo Cliente : "));
P_Fact.add(id_cliente);
P_Fact.add(new Label("Fecha : "));
P_Fact.add(fecha);
P_Fact.add(incluir);
P_Fact.add(terminar);
num_factura.setEditable(true);
cod_vendedor.setEditable(true);
id_cliente.setEditable(true);
fecha.setEditable(true);
add(P_Fact);
setVisible(true);
}
private void insertar_fila()
{
try{
conexion = (Connection)DriverManager.getConnection("jdbc:oracle:thin:@IP:PUERTO:NOMBREDB","USUARIO","PASSWORD");
sentencia=conexion.createStatement();
sentencia.executeUpdate("INSERT INTO Factura"+
" VALUES ('"+num_factura.getText()+"',"+
"'"+cod_vendedor.getText()+"',"+
"'"+id_cliente.getText()+"',"+
"'"+fecha.getText()+"')");
}
catch(Exception e){
}
finally{
try{
sentencia.close();
conexion.close();
}catch(Exception e){
}
}
}
public void actionPerformed(ActionEvent e)
{ String com=e.getActionCommand();
if ("Incluir".equals(com))
{insertar_fila();
num_factura.setText("");
cod_vendedor.setText("");
id_cliente.setText("");
fecha.setText("");
}
else
{
if(conexion!=null)
{
try
{
conexion.close();
}
catch(SQLException ex){}
}
dispose();
}
}
}
//Clase consultar
import java.awt.*;
import java.sql.*;
import java.awt.event.*;
class Consultar extends Dialog implements ActionListener
{
private Connection conexion;
private Statement sentencia;
private ResultSet resultado;
private Button siguiente, terminar;
private TextField num_factura,cod_vendedor,id_cliente, fecha;
Consultar(Frame f)
{
super(f,"Consultar datos",true);
setSize(320,180);
num_factura=new TextField(20);
cod_vendedor=new TextField(20);
id_cliente=new TextField(20);
fecha=new TextField(20);
siguiente=new Button("Siguiente");
siguiente.addActionListener(this);
terminar=new Button("Terminar");
terminar.addActionListener(this);
Panel P_Datos=new Panel();
P_Datos.add(new Label("Numero Factura : "));
P_Datos.add(num_factura);
P_Datos.add(new Label("Código Vendedor : "));
P_Datos.add(cod_vendedor);
P_Datos.add(new Label("Cliente : "));
P_Datos.add(id_cliente);
P_Datos.add(new Label("Fecha : "));
P_Datos.add(fecha);
P_Datos.add(siguiente);
P_Datos.add(terminar);
add(P_Datos);
num_factura.setEditable(false);
cod_vendedor.setEditable(false);
id_cliente.setEditable(false);
fecha.setEditable(false);
mostrar();
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{ String com=e.getActionCommand();
if ("Siguiente".equals(com))
siguiente();
else
{
if (conexion!=null)
{
try
{
sentencia.close();
conexion.close();
}
catch(SQLException ex){}
}
dispose();
}
}
private void mostrar()
{
try{
conexion = (Connection)DriverManager.getConnection("jdbc:oracle:thin:@IP:PUERTO:NOMBREDB","USUARIO","PASSWORD");
sentencia=conexion.createStatement();
resultado=sentencia.executeQuery("SELECT * FROM Factura");
siguiente();
}
catch(Exception e){
try{
sentencia.close();
conexion.close();
}catch(Exception e1){}
}
}
private void consultar_Datos()
{ try
{
num_factura.setText(resultado.getString("num_factura"));
cod_vendedor.setText(resultado.getString("cod_vendedor"));
id_cliente.setText(resultado.getString("id_cliente"));
fecha.setText(resultado.getString("fecha"));
}
catch (SQLException e){}
}
private void siguiente()
{ try
{
if (resultado.next()) consultar_Datos();
}
catch(SQLException e){}
catch(Exception ex){}
}
}
//Clase Borrar
import java.awt.*;
import java.sql.*;
import java.awt.event.*;
class Borrar extends Dialog implements ActionListener
{
private Connection conexion;
private Statement sentencia;
private Statement sentencia_borrar;
private ResultSet resultado;
private Button borrar,siguiente,terminar;
private TextField num_factura, cod_vendedor,id_cliente,fecha;
Borrar(Frame f)
{ super(f,"Borrar datos",true);
setSize(320,180);
num_factura=new TextField(20);
cod_vendedor=new TextField(20);
id_cliente=new TextField(20);
fecha=new TextField(20);
borrar=new Button("Borrar");
borrar.addActionListener(this);
siguiente=new Button("Siguiente");
siguiente.addActionListener(this);
terminar=new Button("Terminar");
terminar.addActionListener(this);
Panel P_Fact=new Panel();
P_Fact.add(new Label("Número Factura : "));
P_Fact.add(num_factura);
P_Fact.add(new Label("Codigo Vendedor : "));
P_Fact.add(cod_vendedor);
P_Fact.add(new Label("Codigo Cliente : "));
P_Fact.add(id_cliente);
P_Fact.add(new Label("Fecha : "));
P_Fact.add(fecha);
P_Fact.add(borrar);
P_Fact.add(siguiente);
P_Fact.add(terminar);
add(P_Fact);
num_factura.setEditable(false);
cod_vendedor.setEditable(false);
id_cliente.setEditable(false);
fecha.setEditable(false);
mostrar();
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{ String com=e.getActionCommand();
if ("Siguiente".equals(com)){
siguiente();
}
else{
if ("Borrar".equals(com)){
borrar_registro();
}
else{
if (conexion!=null){
try{
sentencia.close();
conexion.close();
}
catch(SQLException ex){}
}
dispose();
}
}
}
private void mostrar()
{
try{
conexion = (Connection)DriverManager.getConnection("jdbc:oracle:thin:@IP:PUERTO:NOMBREDB","USUARIO","PASSWORD");
sentencia=conexion.createStatement();
resultado=sentencia.executeQuery("SELECT * FROM Factura");
siguiente();
}
catch(Exception e){
try{
sentencia.close();
conexion.close();
}catch(Exception e1){}
}
}
private void borrar_registro()
{
try{
conexion = (Connection)DriverManager.getConnection("jdbc:oracle:thin:@IP:PUERTO:NOMBREDB","USUARIO","PASSWORD");
sentencia_borrar=conexion.createStatement();
sentencia_borrar.executeUpdate("delete from Factura where num_factura like '"+num_factura.getText()+"'");
num_factura.setText("");
cod_vendedor.setText("");
id_cliente.setText("");
fecha.setText("");
}
catch(SQLException e){}
finally{
try{
sentencia_borrar.close();
}catch(Exception e){
}
}
}
private void consultar_Datos()
{ try
{
num_factura.setText(resultado.getString("num_factura"));
cod_vendedor.setText(resultado.getString("cod_vendedor"));
id_cliente.setText(resultado.getString("id_cliente"));
fecha.setText(resultado.getString("fecha"));
}
catch (SQLException e){}
}
private void siguiente()
{ try
{
if (resultado.next()) consultar_Datos();
}
catch(SQLException e){}
catch(Exception ex){}
}
}
//Clase Actualizar
import java.awt.*;
import java.sql.*;
import java.awt.event.*;
class Actualizar extends Dialog implements ActionListener
{
private Connection conexion;
private Statement sentencia;
private Statement sentencia_borrar;
private ResultSet resultado;
private Button actualizar,siguiente,terminar;
private TextField num_factura, cod_vendedor,id_cliente,fecha;
Actualizar(Frame f)
{ super(f,"Actualizar datos",true);
setSize(320,180);
num_factura=new TextField(20);
cod_vendedor=new TextField(20);
id_cliente=new TextField(20);
fecha=new TextField(20);
actualizar=new Button("Actualizar");
actualizar.addActionListener(this);
siguiente=new Button("Siguiente");
siguiente.addActionListener(this);
terminar=new Button("Terminar");
terminar.addActionListener(this);
Panel P_Fact=new Panel();
P_Fact.add(new Label("Número Factura : "));
P_Fact.add(num_factura);
P_Fact.add(new Label("Codigo Vendedor : "));
P_Fact.add(cod_vendedor);
P_Fact.add(new Label("Codigo Cliente : "));
P_Fact.add(id_cliente);
P_Fact.add(new Label("Fecha : "));
P_Fact.add(fecha);
P_Fact.add(actualizar);
P_Fact.add(siguiente);
P_Fact.add(terminar);
add(P_Fact);
num_factura.setEditable(true);
cod_vendedor.setEditable(true);
id_cliente.setEditable(true);
fecha.setEditable(true);
mostrar();
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{ String com=e.getActionCommand();
if ("Siguiente".equals(com)){
siguiente();
}
else{
if ("Actualizar".equals(com)){
actualiza_registro();
}
else{
if (conexion!=null){
try{
sentencia.close();
conexion.close();
}
catch(SQLException ex){}
}
dispose();
}
}
}
private void mostrar()
{
try{
conexion = (Connection)DriverManager.getConnection("jdbc:oracle:thin:@IP:PUERTO:NOMBREDB","USUARIO","PASSWORD");
sentencia=conexion.createStatement();
resultado=sentencia.executeQuery("SELECT * FROM Factura");
siguiente();
}
catch(Exception e){
try{
System.out.println(e);
sentencia.close();
conexion.close();
}catch(Exception e1){}
}
}
private void actualiza_registro()
{
try{
conexion = (Connection)DriverManager.getConnection("jdbc:oracle:thin:@IP:PUERTO:NOMBREDB","USUARIO","PASSWORD");
sentencia_borrar=conexion.createStatement();
sentencia_borrar.executeUpdate(
"UPDATE Factura SET "+
" num_factura = '" + num_factura.getText() +"'"+
", cod_vendedor = '" + cod_vendedor.getText() +"'"+
", id_cliente = '" + id_cliente.getText() +"'"+
", fecha = '" + fecha.getText() +"'"+
" where num_factura like '"+num_factura.getText()+"'"
);
}
catch(Exception e1){
System.out.println(e1);
}
finally{
try{
sentencia_borrar.close();
}catch(Exception e){
}
}
}
private void consultar_Datos()
{ try
{
num_factura.setText(resultado.getString("num_factura"));
cod_vendedor.setText(resultado.getString("cod_vendedor"));
id_cliente.setText(resultado.getString("id_cliente"));
fecha.setText(resultado.getString("fecha"));
}
catch (SQLException e){}
}
private void siguiente()
{ try
{
if (resultado.next()) consultar_Datos();
}
catch(SQLException e){}
catch(Exception ex){}
}
}
Salu2.
Respuesta
1
Siento mucho no poder ayudarte, pero yo nunca he trabajado con Java conectándolo a Access y Oracle, sólo a Mysql.
En lo único en que tal vez te puedo ayudar es en borrar y modificar.
Yo para borrar no uso Drop table como veo que tú utilizas ya que nunca he tenido la necesidad de borrar una tabla completa, es por eso que utilizo delete. Por ejemplo: Delete from tablar where parametro='" + variable + "'"
Y para modificar no utilizo el update sino que si quiero modificar un registro en específico, primero lo busco con select, luego lo borro con delete y luego lo vuelvo a insertar con insert en la posicion que estaba. No sé si es muy rebuscado pero así fue como me funcionó a mi.
Espero haberte servido de algo.
Suerte!
Daniel J. Giménez A.
Respuesta
1
Me gustaria saber si este programa te ha arrojado algun error o simplemente no ejecuta lo que quieres.
Puedes tener varios casos de errores.
1. Error de conexion, lo que aparentemente no deberia ocurrir ya que el codigo de conexion se ve bien.
La pregunta seria, ¿has registrado la BD en el DNS del sistema?, ya que estas usando el puente jdbc:odbc.
2. Error de sql, donde la sentencia esta mal escrita.
3. O simplemente que no estas enviando los parametros correspondientes, por ejemplo, un int en lugar de un string.
La sentencia sql para realizar un update es:
UPDATE table_name //tabla a actualizar
SET column_name = new_value (en caso se ser varios campos se separan con comas)
WHERE column_name = some_value // condicion por la que filtra la actualizacion
la sintaxis para realizar un borrado es la siguiente
DELETE FROM table_name
WHERE column_name = some_value
tambien puedes fijarte estas paginas, tal vez te ayuden
http://www.programacion.com/bbdd/tutorial/jdbc/
www.tic.udc.es/~fbellas/ teaching/is/Tema2Apartado2.1.pdf
www.tic.udc.es/~fbellas/teaching/is/Tema2Apartado0.pdf
http://www.itapizaco.edu.mx/paginas/JavaTut/froufe/parte21/cap21-1.html
Bueno, espero que algo de esto te ayude, sino no dejes de consultarme, e intenta ser mas especifica con los puntos.
Suerte
Respuesta
1
Este tipo de cogido neceista un poco de estudio, pero viendo por encima, puedo decirte que las sentencia para consultar y borrar estan incompletas o no son correctas: la de borrar es:
sentencia.executeUpdate("delete * from Factura where num_factura='"+num_factura.getText()+"'");
sino:
sentencia.executeUpdate("delete from Factura where num_factura='"+num_factura.getText()+"'");
no estoy seguro cual de los dos es correcto; la de consulta debe ser asi:
resultado=sentencia.executeQuery("SELECT * FROM Factura where num:factura='"+num_factura.getText()+"'");
Las lineas anteriores son para que puedas decirle a la base de datos cual tupla o fila debe borrar exactamente.
Si sucede algo mas, escribe...
Respuesta
1
Primero debo de recomendarte que revises la estructura del programa, no es la forma adecuada de tratar el problema. Pero primero solucionemos el problema. Si revisas tu sentencia sql de borrado:
delete from Factura where
VALUES (... )
Si revisas un poco SQL veras que la sentencia no es correcta, deberias de poner algo como :
"delete from factura where
num_factura = " + .. +
" and cod_vendedor = " + ....
etc
revisa a eso y veras como sí va.
Referente a lo que te comenté al principio, la forma habitual de hacerlo es mediante una capa de acceso a dato. Algo, por ejemplo, asi :
clase BaseDatos {
public void borrar(Factura fact) throws Exception {
.....
}
public void insertar (Factura fact) throws Exception {
....
public Factura[] consultaTodos () throws Exception { ...
// Recorres el resutset y
// lo vas almacenando en un
// array
}
Creas una clase Factura con todos los campos de la factura .
Y luego en los frames, en lugar de abrir la conexion, cerrarla, etc ... haces una llamada al metodo de la clase de Base de datos que necesitas.
Así te aseguras no dejar conexiones abiertas ni nada por el estilo, ademas de que centras el problema de conexiones y consultas a base de datos en una clase concreta.

Añade tu respuesta

Haz clic para o

Más respuestas relacionadas