Hey galerinha
Estou fazendo um projeto para para a faculdade onde preciso fazer um sistema de controle de entregas.
Para mim fazer a conexão com o banco de dados eu criei uma classe com metodos e atributos estaticos para que ela possa ser acessada por qualquer objeto do sistema.
O meu objetivo é fazer uma classe de facil uso, acesso e eficiente para trabalhar com o banco de dados.
gostaria que vocês dessem uma olhada e me deem alguns pitacos a respeito do que eu possa fazer para deixa-la melhor.
Valew pelo tempo de voces.
[code]package br.mikhas.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public abstract class JdbcSupport {
private static Connection connection;
private static String database;
private static DataSource dataSource;
private static void checkConnection() {
if (dataSource == null)
throw new DataSourceException("There is no DataSource setted.");
}
public static void setDataSource(DataSource source) {
dataSource = source;
setJdbcDrive();
startJdbcConnection();
}
private static void setJdbcDrive() {
try {
Class.forName(dataSource.getDrive());
} catch (ClassNotFoundException e) {
throw new JdbcException("Drive not found: " + dataSource.getDrive(), e);
}
}
private static void startJdbcConnection() {
checkConnection();
try {
connection = DriverManager.getConnection(dataSource.getDatabase());
} catch (SQLException e) {
throw new JdbcException("Error at connecting with DataSource: " + database, e);
}
}
public static void stopJdbcConnection() {
checkConnection();
try {
connection.close();
} catch (SQLException e) {
throw new JdbcException("The connection couldn't be closed.", e);
}
}
@SuppressWarnings("unchecked")
public static List query(String sql, RowMapper mapper) {
checkConnection();
ArrayList resultList = new ArrayList();
Statement statement;
try {
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
resultList.add(mapper.mapResultSet(resultSet));
}
return resultList;
} catch (SQLException e) {
stopJdbcConnection();
throw new JdbcException("Error on executing query: " + sql, e);
}
}
public static void execute(String sql) {
checkConnection();
try {
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
statement.execute(sql);
} catch (SQLException e) {
stopJdbcConnection();
throw new JdbcException("Erro on executing query: " + sql, e);
}
}
}
[/code]