Conexión a SQL por JDBC
Que tal amigos de JavaMexico, espero que esten bien, les comparto un programita que utiliza el JDBC para hacer un CRUD que implementa 3 clases para Crear, Obtener, Actualizar y Borrar lo dividi en 3 paquetes, me funciona bien pero quisiera saber su opinión o si tienen alguna otra manera de hacerlo mejor, apreciaría sus comentarios
Saludos
Marco
************************************************************************************
1.- package crud.bll;
2.- package crud.dal;
3.- package crud.gui;
************************************************************************************
package crud.bll;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* persona.java
* @author Marco Trejo
* Created on 04/01/2012, 06:42:17 PM
*/
import crud.dal.*;
public class persona {
private String nombre;
private String ap_paterno;
private String ap_materno;
private int id;
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getAp_paterno() {
return ap_paterno;
}
public void setAp_paterno(String ap_paterno) {
this.ap_paterno = ap_paterno;
}
public String getAp_materno() {
return ap_materno;
}
public void setAp_materno(String ap_materno) {
this.ap_materno = ap_materno;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public persona(){
}
public void guarda(boolean accion) throws Exception{
try
{
dbaccess db= new dbaccess();
db.getConexion();
db.iniciaTransaccion();
if(accion == true){
db.inserta("INSERT INTO persona VALUES('"+nombre+"','"+ap_paterno+"','"+ap_materno+"')");
}else{
db.inserta("UPDATE persona set nombre='"+nombre+"',paterno='"+ap_paterno+"',materno='"+ap_materno+"' WHERE id="+id+" ");
}
db.ejecutaTransaccion();
db.cierraConexion();
}catch(Exception ex){
throw ex;
}
}
public void eliminar(int _id){
}
}
************************************************************************************
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* dbaccess.java
* @author Marco Trejo
* Created on 04/01/2012, 06:49:13 PM
*/
import java.sql.*;
public class dbaccess {
private Connection con=null;
private String url =
"jdbc:sqlserver://DHV8LYJ1:1434;databaseName=crud;user=nbuser;password=mipassword";
private String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private Statement st=null;
public dbaccess(){
}
public void getConexion() throws SQLException, ClassNotFoundException{
try{
Class.forName(driver);
con = DriverManager.getConnection(url);
}catch (SQLException ex){
throw ex;
}catch(ClassNotFoundException no){
throw no;
}
}
public void cierraConexion() throws SQLException{
try{
if(con!=null){
con.close();
con=null;
}
}catch(SQLException ex){
throw ex;
}
}
public void iniciaTransaccion() throws SQLException{
try{
con.setAutoCommit(false);
}catch(SQLException ex){
throw ex;
}
}
public void cancelaTransaccion() throws SQLException{
try{
con.rollback();
}catch(SQLException ex){
throw ex;
}
}
public void ejecutaTransaccion() throws SQLException{
try{
con.commit();
}catch(SQLException ex){
throw ex;
}
}
public void inserta(String sql) throws SQLException, ClassNotFoundException{
try{
st=con.createStatement();
st.execute(sql);
}catch(SQLException ex){
cancelaTransaccion();
throw ex;
}
finally{
if(st!=null){
st.close();
}
}
}
}
************************************************************************************
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* crudGUI.java
* @author Marco Trejo
* Created on 04/01/2012, 06:50:12 PM
*/
package crud.gui;
import crud.bll.persona;
import java.util.logging.Level;
import java.util.logging.Logger;
public class crudGUI extends javax.swing.JFrame {
/** Creates new form crudGUI */
public crudGUI() {
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")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextField1.setText(" ");
jTextField2.setText(" ");
jTextField3.setText(" ");
jTextField3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField3ActionPerformed(evt);
}
});
jLabel1.setText("Nombre");
jLabel2.setText("Apellido Paterno");
jLabel3.setText("Apellido Materno");
jLabel4.setText("REGISTRO");
jButton1.setText("Guardar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(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(35, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addGap(45, 45, 45)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 126, Short.MAX_VALUE)
.addComponent(jTextField2)
.addComponent(jTextField3)))
.addGap(114, 114, 114))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(146, 146, 146))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addComponent(jLabel4)
.addGap(41, 41, 41)
.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(jLabel1))
.addGap(13, 13, 13)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addGap(40, 40, 40)
.addComponent(jButton1)
.addContainerGap(71, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField3ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField3ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
persona person = new persona();
person.setNombre(jTextField1.getText());
person.setAp_paterno(jTextField2.getText());
person.setAp_materno(jTextField3.getText());
try {
person.guarda(true);
} catch (Exception ex) {
Logger.getLogger(crudGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new crudGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
// End of variables declaration//GEN-END:variables
}
************************************************************************************
- Marco Antonio Trejo Lemus's blog
- Inicie sesión o regístrese para enviar comentarios
Comentarios
Mejoras
Hola:
Yo le agregaria un par de funcionalidades mas
1.- Control del Datasource via JNDI
2.- Usar DBUtils (commons-dbutils) para cerrar los rs y las conn, es mas simple y achica tu codigo.
Las lineas estas:
finally{
if(st!=null){
st.close();
}
}
Se reducen a:
finally{
DBUtils.closeQuietly(st);
}
Acerca del driver
Buenas, en el tiempo que llevo trabajando con SQL Server y Java a mi parecer es mejor utilizar el driver JTDS ya que el driver que proporciona Microsoft no me pudo conectar a una base de datos cuando utilizo JSP's. El JTDS está muy bien ya que puede trabajar con servidores SQL 2000, 2005 y 2008 además de instancias por defecto e instancias normales. Entonces la única sugerencia que haría es que utilizaras ese driver para que quede más completo tu programa, quizás cambiarían algunas líneas de tu código pero en realidad serían como unas 4 cuando mucho.
Saludos...
Sugerencias
Mas que mejoras son sugerencias
Conocimientos base
Pues para mejorar ésto es necesario aprender ciertos conceptos y
conocimientos base. Primero, la conexión, necesitas un patrón de
diseño que se llama Singleton, con ello puedes reutilizar una misma
conexión sin tener que abrir y cerrar, procesos costosos.
De ahí, reparsarte las convenciones del lenguaje como te ha recomendado
@lankor.
Otra cosa es aprender a utilizar otro patrón de diseño llamado, MVC
que te ayuda a separar las 3 capas principales de una aplicación
(modelo, vista y controlador). De ahí, es necesario combinar aun poco
con el otro patrón que se llama DAO.
Para finalizar, solo practicar y ponernos problemas por día, no sé
puedes revisar en Project Euler
o algún sitio similar.
En fin, tienes bastante idea de como hacer las cosas, pero como todos,
tenemos mucho que aprender.