importando archivos csv desarrollado en java con netbeans a mysql eso lo tengo lo que me falta es lo siguiente. gracias de ant..
Cuando haga la importación de csv a mysql por ejemplo tengo 15 registros guardados y luego hago otra importación con 10 registros pero en ese registro hay un dni index campo primario repetido de la primera importación me tiene que decir que ese registro ya existe y que no puede ser ingresado, imaginemos que la secretaria quiera importar unos archivos y sean guardados esos archivos sin esa condición me va guardar todo voy supongamos tenemos un nombre que ya había pasado y me vuelva a guardar ese nombre va ver registros repetidos, eso no debe pasar..
aqui dejo pantallasos explico el primero es el formulario diseño que busca, importa
el segundo es cuando hago click en buscar para generar el archivo donde esta ubicado
luego el boton importar presiono y me dice importado exitosamente
luego esos datos son guardados en mi base de datos
como pueden observar tengo mi 6 campos de mi tabla conforme a mis campos de archivo excel
y mi codigo espero contar con su ayuda ya que son expertos en java de antemano gracias
CLASE IMPORTAR
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Coneccion;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* @author P_HBezemer
*/
public class importar {
Connection conecion = null;
public void importar(String url){
try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String usuario = "root";
String password= "";
String base = "RegistroErrores";
url = url.replace('\\', '/');
conecion = DriverManager.getConnection("jdbc:mysql://localhost/" + base,password, usuario);
PreparedStatement consulta;
try{
consulta = conecion.prepareStatement("LOAD DATA LOCAL INFILE '"+url+"' INTO TABLE respaldo FIELDS TERMINATED BY ';' LINES TERMINATED BY '\n' ");
consulta.executeQuery();
JOptionPane.showMessageDialog(null,"Carga con exito");
}catch(Exception ex){
JOptionPane.showMessageDialog(null,"Error en cargar");
}
}
catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null,"Error en el Driver");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null,"Error en la Conexion");
} catch (InstantiationException ex) {
Logger.getLogger(importar.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(importar.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
FORMULARIO:
import Coneccion.importar;
import java.awt.BorderLayout;
import java.awt.FileDialog;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFileChooser;
import java.sql.*;
import javax.swing.JOptionPane;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author P_HBezemer
*/
public class Charger extends javax.swing.JFrame {
String url;
/**
* Creates new form Charger
*/
public Charger() {
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.
*/
@SuppressWarnings("unchecked")
//
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("Buscar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Cargar");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("Volver");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(34, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
.addComponent(jButton3)
.addContainerGap())
);
pack();
}//
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Main abrir =new Main();
abrir.setVisible(true);
this.dispose();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser dato= new JFileChooser();
int op = dato.showOpenDialog(this);
if(op==JFileChooser.APPROVE_OPTION){
jTextField1.setText(dato.getSelectedFile().getPath());
}
url=dato.getSelectedFile().getPath();
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
importar cs = new importar();
cs.importar(url);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see <a href="http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try" title="http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try">http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html...</a> {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Charger.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Charger.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Charger.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Charger.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Charger().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
bueno ya son las 2:30am y la verdad que asi es nuestro trabajo jeje
espero que me ayuden
Adjunto | Tamaño |
---|---|
busca archivo.png | 51.15 KB |
buscar.png | 98.18 KB |
carga archivo.png | 29.37 KB |
datos guardados.png | 79.03 KB |
- Inicie sesión o regístrese para enviar comentarios
línea por línea
La solución típica es leer el CSV línea por línea y usar JDBC (o este como subyacente). Por cada línea leída, se inserta en la base de datos el registro correspondiente en caso de no existir en la base de datos (previa consulta).
En tu código, cargas el archivo CSV utilizando una instrucción de MySQL. MySQL es quién lee el archivo y dependiendo de las opciones, hace algo con los registro duplicados y, tal vez (¡quién sabe!), lo informa a JDBC como un warning.
lo que te entendi es lo siguiente
sabes te comento antes de contestar a tu respuesta primero gracias por darte el tiempo por analizar mi codigo
bueno ahora que acabo de ver el sistemita hace lo que quiero que no me cargue otro dni que sea halla cargado anteriormente
ya que lo estoy pasando con llave primaria mi cmapo dni hace lo que quiero.. pero
me quede pensando en lo que me dijistes en leer linea por linea concatenado con jdbc me queda la sensacion de que tambien se puede hacer de esa manera pero no lo he intentado para que mentirte...
todos tenemos logicas diferentes y por ende tu logica me tomara una tarea dificil entenderla pero si a ti te funciona lo que me pusistes me lo puedes compartir te lo agradeceria bastante
saludos y exitos capo