Aperfeiçando a coenxão com o banco

Estundando e tentando melhora fiz um código de conexão esta funcionando porém eu gostaria de comentários para melhorar. Esse exemple que fiz é com Statement, depois vou fazer com PreparedStatement.
Então fiz da seguinte forma.
Fiz a class de conexão dessa forma:

/*
 * Conexao.java
 *
 * Created on 22 de Maio de 2007, 21:00
 */

package conexao;
 
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;



/**
 *
 * @author alexandre
 * @version
 */
public class Conexao {
 	
 	private static String NAME	= "com.mysql.jdbc.Driver";
 	private static String URL	= "jdbc:mysql://localhost/basedados";
 	private static String LOGIN	= "root";
 	private static String PASS	= "";
        private static Connection conn;
 	
 	/**
 	 * 
 	 * @return Conexao.
 	 * @throws SQLException
 	 * @throws IOException
 	 */
 	public static Connection connect() throws SQLException, IOException {
 		
 		try {
 			Class.forName(NAME);
 			conn = DriverManager.getConnection(URL, LOGIN, PASS);
 		} catch (ClassNotFoundException e) {
 			System.out.print("\nNão foi possível estabelecer conexão com a base de dados.\n");
 			e.printStackTrace();
 			return null;
 		}
 		return conn;
 	}
 }

E uso essa conexão em outra class da seguinte forma:

/*
 * DAO_usuario.java
 *
 * Created on 22 de Maio de 2007, 21:44
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package DAO;

import java.io.*;
import java.net.*;
import java.util.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;

import conexao.Conexao;

/**
 *
 * @author alexandre
 */
public class DAO_usuario 
{
    
    public String usuario;
    public String senha;
    public String consulta;
    public String logado;
    public String outros;
    
    private ResultSet rs;
    private Connection conn;
    private Statement sql;
  
    
      
    public void DAO_dados(String getUsuario, String getSenha) throws SQLException, IOException
    {
      
            conn = Conexao.connect(); 
            sql = conn.createStatement();   
            
            
            usuario = getUsuario; 
            senha = getSenha;
       
            consulta = "select * from senhadeals where senha='"+senha+"' and usuario='"+usuario+"' limit 1  ";
            
            
            rs = sql.executeQuery(consulta);
            
            
            while(rs.next())
            {
                logado = rs.getString("nome");
            }
        
        
        
       
    }

   public void DAO_outros(String getOutros) throws SQLException, IOException
    {
      
            conn = Conexao.connect(); 
            sql = conn.createStatement();   
            
            
            outros = getOutros; 

            consulta = "select * from tabela2 where outros='"+outros+"'  limit 1  ";
            
            
            rs = sql.executeQuery(consulta);
            
            
            while(rs.next())
            {
                resultado = rs.getString("outros");
            }
        
        
        
       
    }
    
    public String setLogado()
    {
        return logado;
    }

    public String setOutros()
    {
        return outros;
    }
    
    
}

Eu tenho a class que faz a conexão e a class que usa a conexão. O código esta funcionando. Acho apenas que essa class DAO_usuario tem uma falha não sei se é uma falha ou se é dessa forma mesmo! Eu me refiro ao seguinte eu tenho dois métodos que são:
1) public void DAO_dados(String getUsuario, String getSenha) throws SQLException, IOException
2) public void DAO_outros(String getOutros) throws SQLException, IOException

Em cada um desses métodos eu chamo o comando:
conn = Conexao.connect();
Tenho que chamar ele em cada método mesmo ou tem alguma forma de chamar ele apenas em algum lugar dessa classe e ja sirva para todos os métodos? É a única dúvida que ficou.

Dicas para melhorar sua aplicação:

1 Se sua aplicação for para web crie um Pool de conexões;

2 Sempre use PreparedStament;

3 Não programe orientado a Strings
de

DAO_dados(String getUsuario, String getSenha){}

para

login(Usuario usuario){}
    

4 Métodos sempre começam com letras minúsculas

Dê uma olhada nessa minha classe chamada BaseDAO, ela implementa as funcionalidades básicas de conexão com o banco de dados:

package br.com.unilocsys.persistence.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import br.com.unilocsys.exception.DAOException;
import br.com.unilocsys.system.Configuration;

/**
 * Classe Abstrata que contém os métodos de acesso ao banco de dados.
 * Esses métodos são herdados pelas outras classe que necessitem desse acesso.
 */
public abstract class BaseDAO {

	// nome do Driver JDBC
	private String driver;
	
	// url de conexão com o banco de dados
	private String url;
	
	// usuario
	private String user;
	
	// senha
	private String pwd;
	
	// numero de tentativas de conexão
	private int retry;
	
	// interface que recebe a conexão com o banco de dados
	private Connection connection;

	/**
	 * Costrutor default da classe
	 * @throws DAOException
	 */
	public BaseDAO() throws DAOException {

		// carrega as configurações do sistema
		Configuration configuration = Configuration.getInstance();
		Properties properties = configuration.getProperties();
		
		// seta as variaveis utilizadas no processo
		this.driver = properties.getProperty("jdbc.driver");
		this.url = properties.getProperty("jdbc.url");
		this.user = properties.getProperty("jdbc.user");
		this.pwd = properties.getProperty("jdbc.pwd");
		this.retry = Integer.parseInt(properties.getProperty("jdbc.retry").trim());
		
		try {
		
			// carrega o Driver JDBC
			Class.forName(this.driver);
					
		} catch (ClassNotFoundException e) {
			throw new DAOException("Driver JDBC não encontrado");
		}				
	}

	/**
	 * Método que retorna uma conexão com o banco de dados
	 * @throws DAOException
	 */
	protected Connection getConnection() throws DAOException {
		if (!connect()) {
			throw new DAOException("Falha ao conectar no Banco de Dados");
		}
		return connection;
	}
	
	/**
	 * Método que efetuas as tentativas de conexão 
	 */
	private boolean connect() throws DAOException {
		for (int i = 0; i < this.retry; i++) {
			try {
				
				// tenta estabelecer uma conexão com o banco de dados
				connection = DriverManager.getConnection(url, user, pwd);
				return true;
				
			} catch (SQLException e) {
				
				System.out.println("Conectando no Banco de Dados... Tentativa " + (i+1) + " de " + this.retry);
				
				try {
					// aguarda 3 seg antes de tentar novamente
					Thread.sleep(3000);
				} catch (InterruptedException ee) {
					throw new DAOException("Falha no sistema");
				}
			}
		}		
		return false;
	}
	
	/**
	 * Método sobrecarregado que fecha uma Connection
	 * e um PreparedStatement  
	 * @throws DAOException
	 */
	protected void closeConnection(PreparedStatement statement) throws DAOException {
		try {
			closeStatement(statement);
			closeConnection(connection);
		} catch (SQLException e) {
			throw new DAOException("Erro ao fechar a conexão com o Banco de Dados");
		}
	}
	
	/**
	 * Método sobrecarregado que fecha uma Connection,
	 * um PreparedStatement e um ResultSet
	 * @throws DAOException
	 */
	protected void closeConnection(PreparedStatement statement, ResultSet resultSet) throws DAOException {
		try {
			closeStatement(statement);
			closeResult(resultSet);
			closeConnection(connection);
		} catch (SQLException e) {
			throw new DAOException("Erro ao fechar a conexão com o Banco de Dados");
		}
	}
	
	/**
	 * Método que fecha um PreparedStatement
	 * @throws SQLException
	 */
	private void closeStatement(PreparedStatement statement) throws SQLException {
		if (statement != null) {
			statement.close();
		}
	}
	
	/**
	 * Método que fecha um ResultSet
	 * @throws SQLException
	 */
	private void closeResult(ResultSet resultSet) throws SQLException {
		if (resultSet != null) {
			resultSet.close();
		}
	}
	
	/**
	 * Método que fecha uma Connection
	 * @throws SQLException
	 */
	private void closeConnection(Connection connection) throws SQLException {
		if (connection != null) {
			connection.close();
		}
	}
	
}

e aqui, um exemplo de utilização:

package br.com.unilocsys.persistence.dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

import br.com.unilocsys.exception.DAOException;
import br.com.unilocsys.model.bean.ClienteBean;
import br.com.unilocsys.model.type.Cliente;

/**
 * Classe responsável em persistir
 * os dados do cliente no banco de dados
 */
public class ClienteDAO extends BaseDAO {

	private static final String INSERT = 
		""
		.concat("insert into Cliente \n")
		.concat("	(cod_cli, nome_cli, nascimento_cli, rg_cli, cpf_cli, sexo_cli, email_cli, foto_cli, end_cli, num_cli, bairro_cli, cidade_cli, uf_cli, cep_cli, comp_cli) \n")
		.concat("	values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) \n");
		
	private static final String SELECT_BY_COD = 
		""
		.concat("select * \n")
		.concat("	from Cliente \n")
		.concat(" where cod_cli = ? \n");
	
    private static final String SELECT_ALL =
    	""
		.concat("select * \n")
		.concat("	from Cliente \n");
	
    private static final String UPDATE = 
    	""
    	.concat("update Cliente \n")
    	.concat("	set nome_cli = ?, \n")
    	.concat("		nascimento_cli = ?, \n")
    	.concat("		rg_cli = ?, \n")
    	.concat("		cpf_cli = ?, \n")
    	.concat("		sexo_cli = ?, \n")
    	.concat("		email_cli = ?, \n")
    	.concat("		foto_cli = ?, \n")
    	.concat("		end_cli = ?, \n")
    	.concat("		num_cli = ?, \n")
    	.concat("		bairro_cli = ?, \n")
    	.concat("		cidade_cli = ?, \n")
    	.concat("		uf_cli = ?, \n")
    	.concat("		cep_cli = ?, \n")
    	.concat("		comp_cli = ? \n")    	
    	.concat(" where cod_cli = ? \n");    	
		
	private static final String DELETE = 
		""
		.concat("delete from Cliente \n")
		.concat(" where cod_cli = ? \n");
	
	/**
	 * Construtor default da classe
	 * @throws DAOException
	 */
	public ClienteDAO() throws DAOException {
		super();		
	}

	/**
	 * Método que insere um cliente no banco de dados
	 * @throws DAOException
	 */
	public void insert(ClienteBean clienteBean) throws DAOException {
		
		PreparedStatement statement = null;
		Connection connection = null;
		
		try {
			
			connection = this.getConnection();
			statement = connection.prepareStatement(INSERT);
			
			statement.setInt(1, clienteBean.getCod());
			statement.setString(2, clienteBean.getNome());
			statement.setDate(3, new Date(clienteBean.getNascimento().getTime()));
			statement.setString(4, clienteBean.getRg());
			statement.setString(5, clienteBean.getCpf());
			statement.setString(6, clienteBean.getSexo());
			statement.setString(7, clienteBean.getEmail());
			statement.setBytes(8, clienteBean.getFoto());
			statement.setString(9, clienteBean.getEndereco().getEndereco());
			statement.setString(10, clienteBean.getEndereco().getNum());
			statement.setString(11, clienteBean.getEndereco().getBairro());
			statement.setString(12, clienteBean.getEndereco().getCidade());
			statement.setString(13, clienteBean.getEndereco().getUf());
			statement.setString(14, clienteBean.getEndereco().getCep());
			statement.setString(15, clienteBean.getEndereco().getComplemento());
			
			statement.execute();
			
		} catch (SQLException e) {
			throw new DAOException("Erro ao inserir o Cliente"); 
		} finally {
			this.closeConnection(statement);
		}
	}
	
	/**
	 * Método que retorna um cliente especifico do banco de dados
	 * @throws DAOException
	 */
	public ClienteBean select(Cliente cliente) throws DAOException {
		
		PreparedStatement statement = null;
		Connection connection = null;
		ResultSet resultSet = null;
		ClienteBean clienteBean = null;
				
		try {
			
			connection = this.getConnection();
			statement = connection.prepareStatement(SELECT_BY_COD);
			
			statement.setInt(1, cliente.getCod());
			
			resultSet = statement.executeQuery();
			
			if (resultSet.next()) {
				
				clienteBean = new ClienteBean();
				
				clienteBean.setCod(resultSet.getInt("cod_cli"));
				clienteBean.setNome(resultSet.getString("nome_cli"));
				clienteBean.setNascimento(resultSet.getDate("nascimento_cli"));
				clienteBean.setRg(resultSet.getString("rg_cli"));
				clienteBean.setCpf(resultSet.getString("cpf_cli"));
				clienteBean.setSexo(resultSet.getString("sexo_cli"));
				clienteBean.setEmail(resultSet.getString("email_cli"));
				clienteBean.setFoto(resultSet.getBytes("foto_cli"));
				clienteBean.getEndereco().setEndereco(resultSet.getString("end_cli"));
				clienteBean.getEndereco().setNum(resultSet.getString("num_cli"));
				clienteBean.getEndereco().setBairro(resultSet.getString("bairro_cli"));
				clienteBean.getEndereco().setCidade(resultSet.getString("cidade_cli"));
				clienteBean.getEndereco().setUf(resultSet.getString("uf_cli"));
				clienteBean.getEndereco().setCep(resultSet.getString("cep_cli"));
				clienteBean.getEndereco().setComplemento(resultSet.getString("comp_cli"));
				
			}
			
		} catch (SQLException e) {
			throw new DAOException("Erro ao localizar o Cliente"); 
		} finally {
			this.closeConnection(statement, resultSet);
		}				
		return clienteBean;
	}
	
	/**
	 * Método que retorna todos os clientes do banco de dados
	 * @throws DAOException
	 */
	public Collection<ClienteBean> select() throws DAOException {
		
		PreparedStatement statement = null;
		Connection connection = null;
		ResultSet resultSet = null;
		ClienteBean clienteBean = null;
		Collection<ClienteBean> clienteList = new ArrayList<ClienteBean>();
		
		try {
			
			connection = this.getConnection();
			statement = connection.prepareStatement(SELECT_ALL);
						
			resultSet = statement.executeQuery();
						
			while (resultSet.next()) {
				
				clienteBean = new ClienteBean();
				
				clienteBean.setCod(resultSet.getInt("cod_cli"));
				clienteBean.setNome(resultSet.getString("nome_cli"));
				clienteBean.setNascimento(resultSet.getDate("nascimento_cli"));
				clienteBean.setRg(resultSet.getString("rg_cli"));
				clienteBean.setCpf(resultSet.getString("cpf_cli"));
				clienteBean.setSexo(resultSet.getString("sexo_cli"));
				clienteBean.setEmail(resultSet.getString("email_cli"));
				clienteBean.setFoto(resultSet.getBytes("foto_cli"));
				clienteBean.getEndereco().setEndereco(resultSet.getString("end_cli"));
				clienteBean.getEndereco().setNum(resultSet.getString("num_cli"));
				clienteBean.getEndereco().setBairro(resultSet.getString("bairro_cli"));
				clienteBean.getEndereco().setCidade(resultSet.getString("cidade_cli"));
				clienteBean.getEndereco().setUf(resultSet.getString("uf_cli"));
				clienteBean.getEndereco().setCep(resultSet.getString("cep_cli"));
				clienteBean.getEndereco().setComplemento(resultSet.getString("comp_cli"));
				
				clienteList.add(clienteBean);
			}
			
		} catch (SQLException e) {
			throw new DAOException("Erro ao carregar todos os Clientes"); 
		} finally {
			this.closeConnection(statement, resultSet);
		}		
		return clienteList;
	}
	
	/**
	 * Método que atualiza um cliente no banco de dados
	 * @throws DAOException
	 */
	public void update(ClienteBean clienteBean) throws DAOException {
		
		PreparedStatement statement = null;
		Connection connection = null;
				
		try {
			
			connection = this.getConnection();
			statement = connection.prepareStatement(UPDATE);
			
			statement.setString(1, clienteBean.getNome());
			statement.setDate(2, new Date(clienteBean.getNascimento().getTime()));
			statement.setString(3, clienteBean.getRg());
			statement.setString(4, clienteBean.getCpf());
			statement.setString(5, clienteBean.getSexo());
			statement.setString(6, clienteBean.getEmail());
			statement.setBytes(7, clienteBean.getFoto());
			statement.setString(8, clienteBean.getEndereco().getEndereco());
			statement.setString(9, clienteBean.getEndereco().getNum());
			statement.setString(10, clienteBean.getEndereco().getBairro());
			statement.setString(11, clienteBean.getEndereco().getCidade());
			statement.setString(12, clienteBean.getEndereco().getUf());
			statement.setString(13, clienteBean.getEndereco().getCep());
			statement.setString(14, clienteBean.getEndereco().getComplemento());
			statement.setInt(15, clienteBean.getCod());
			
			statement.execute();					
			
		} catch (SQLException e) {
			throw new DAOException("Erro ao atualizar o Cliente");			
		} finally {
			this.closeConnection(statement);
		}				
	}

	/**
	 * Método que remove um cliente do banco de dados
	 * @throws DAOException
	 */
	public void delete(Cliente cliente) throws DAOException {
		
		PreparedStatement statement = null;
		Connection connection = null;
		
		try {
			
			connection = this.getConnection();
			statement = connection.prepareStatement(DELETE);
			
			statement.setInt(1, cliente.getCod());
			
			statement.execute();
			
		} catch (SQLException e) {
			throw new DAOException("Erro ao remover o Cliente"); 
		} finally {
			this.closeConnection(statement);
		}		
	}
	
}

qualquer dúvida… :lol: …estamos aqui…

Valeu pela força pessoal, consegui fazer colocando a seguinte expressão:
[b]
public DAO
{
conn = conexao.Conect
}

at+