Galera estou desenvolvendo uma classe que não e nehum framework(não pro enquanto) e simplismente uma classe para contornar o problema que o MySQL possui em relacionamentos e etc ... e de quebra botar minha aplciação OO, mais estou com umas duvidas em ums pontos ... to postando o codigo fonte aqui desculpe-me a porqueira(Codigo feito as pressas) ele e GPL então podem copiar :D, ele tem o intuito de fazwer o seguinte, Criar chaves primarias e estrangeiras para a tabela e fazer atualizações em cascatta nas tabelas relacionadas a ela. a classe e bem simples olhem deem suas opiniões no final vamos ter uma classe muito boa !!!!
ESPIRITO GPL PESSOAL !!!!!
Segue a baixo a classe Database:package sicla.sgbd;
import javax.swing.JOptionPane;
import java.sql.*;
/**
* @author William Jammes de Oliveira
* @version 1.0
*
* Modulo: Gerenciador do Banco de Dados
* Data: 20/11/2002
* Alteração:
*/
public class Database {
private static Connection conn = null;
private static Database db = null;
private Database(String Host,String Db,String User,String Pass) {
try {
Class.forName("org.gjt.mm.mysql.Driver");
} catch (ClassNotFoundException e) {
JOptionPane.showMessageDialog(null,e.toString());
System.exit(1);
}
try {
conn = DriverManager.getConnection("jdbc:mysql://" + Host +"/" + Db, User, Pass);
} catch (SQLException e) {
JOptionPane.showMessageDialog(null,e.toString());
System.exit(1);
}
}
// Retorna a conexão atual
public Connection getConn() {
return conn;
}
//Retorna uma instancia de DB
public static Database getDataBase() {
if (db == null) {
db = new Database("localhost", "sicla", "root", "4991rs97");
}
return db;
}
public Statement getStatement() throws SQLException {
return conn.createStatement();
}
public PreparedStatement getPreparedStatement(String SQL) throws SQLException {
return conn.prepareStatement(SQL);
}
public void close() throws SQLException {
conn.close();
}
public void finalize(){
try {
conn.close();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null,e.toString());
System.exit(1);
}
}
}
Esta e a classse Tabela:
package sicla.sgbd;
/*
*
* Modulo: TbUsuarios
* Descrição: Tabela de controle dos usuarios
*
* Created on 7 de Janeiro de 2003, 14:35
*/
/**
* @author William Jammes de Oliveira
*/
import java.sql.*;
import java.math.*;
class PrimaryKey {
private int PKey = 0;
private Object Tabela = null;
public PrimaryKey(int FKey) {
this.PKey=PKey;
}
public void setKey(int PKey) {
this.PKey=PKey;
}
public int getKey() {
return this.PKey;
}
}
class ForeingKey {
private int FKey = 0;
private PrimaryKey[] PKey;
private Object Tabela = null;
public ForeingKey(int FKey, Tabela Relacionamento) {
this.FKey=FKey;
this.Tabela=Tabela;
this.PKey=Relacionamento.getPrimaryKey();
}
public void setPrimaryKey(PrimaryKey[] PKey) {
this.PKey = PKey;
}
public void setKey(int FKey) {
this.FKey=FKey;
}
public void setTabela(Object Tabela) {
this.Tabela=Tabela;
}
}
public class Tabela {
public static final int INT =0;
public static final int LONG =1;
public static final int STRING =2;
private Connection conn = null;
private ResultSet rs = null;
private PreparedStatement ps = null;
private String NomeTabela = "";
private String[] SQL;
private PrimaryKey[] PKey;
private ForeingKey[] FKey;
/** Creates a new instance of TbUsuarios */
public Tabela(Connection conn, String NomeTabela ,String[] SQLs) {
this.conn = conn;
this.SQL = SQLs;
this.NomeTabela = NomeTabela;
try {
this.getRegistros();
}catch(SQLException e){javax.swing.JOptionPane.showMessageDialog(null,e.toString());}
}
public boolean next() {
try {
rs.next();
}catch(SQLException e){return false;}
return true;
}
public boolean previous() {
try {
rs.previous();
}catch(SQLException e){return false;}
return true;
}
public boolean first() {
try {
rs.first();
}catch(SQLException e){return false;}
return true;
}
public boolean last() {
try {
rs.last();
}catch(SQLException e){System.out.println(e.toString());}
return true;
}
public void setPrimaryKey(PrimaryKey[] PKey) {
this.PKey = PKey;
}
public void setForeingKey(ForeingKey[] FKey) {
this.FKey = FKey;
}
public PrimaryKey[] getPrimaryKey() {
return this.PKey;
}
public ForeingKey[] getForeingKey() {
return this.FKey;
}
public ResultSet getRegistros() throws SQLException {
//Statement stm = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
Statement stm = conn.createStatement();
rs = stm.executeQuery(SQL[0]);
return rs;
}
public ResultSet getRegistros(String SQL) throws SQLException {
Statement stm = conn.createStatement();
rs = stm.executeQuery(SQL);
return rs;
}
public long getGenerator(int coluna, int tipo) {
long retorno=0;
try {
rs.last();
}catch(SQLException e){
javax.swing.JOptionPane.showMessageDialog(null,"1:" + e.toString());
return (retorno+1);
}
try{
switch(tipo) {
case 0:
retorno=(long)rs.getInt(coluna);
break;
case 1:
retorno=rs.getLong(coluna);
break;
}
}catch(SQLException e){
javax.swing.JOptionPane.showMessageDialog(null,"2:" + e.toString());
return (retorno+1);
}
return (retorno+1);
}
public boolean insert() {
try {
ps = conn.prepareStatement(SQL[1]);
}catch(SQLException e){return false;}
return true;
}
public boolean edit() {
try {
ps = conn.prepareStatement(SQL[2]);
}catch(SQLException e){return false;}
return true;
}
public boolean remove() {
try {
for(int i=0;i<this.PKey.length;i++) {
this.set(this.PKey[i].getKey(),rs.getInt(this.PKey[i].getKey()));
}
ps = conn.prepareStatement(SQL[3]);
}catch(SQLException e){return false;}
return true;
}
public boolean update() {
try {
ps.execute();
}catch(SQLException e){return false;}
return true;
}
public boolean cancel() {
try {
ps = null;
}catch(NullPointerException e){return false;}
return true;
}
public boolean set( int coluna , Object valor ){
try {
ps.setObject(coluna,valor);
}catch(SQLException e){return false;}
return true;
}
public boolean setNull(int coluna, int Tipo) {
try {
ps.setNull(coluna, Tipo);
}catch(SQLException e){return false;}
return true;
}
public boolean set( int coluna , int valor ){
try {
ps.setInt(coluna, valor);
}catch(SQLException e){return false;}
return true;
}
public boolean set( int coluna , double valor ){
try {
ps.setDouble(coluna, valor);
}catch(SQLException e){return false;}
return true;
}
public boolean set( int coluna , long valor ){
try {
ps.setLong( coluna, valor);
}catch(SQLException e){return false;}
return true;
}
public boolean set( int coluna , String valor ){
try {
ps.setString( coluna, valor);
}catch(SQLException e){return false;}
return true;
}
public boolean set( int coluna , float valor ){
try {
ps.setFloat( coluna, valor);
}catch(SQLException e){return false;}
return true;
}
public boolean set( int coluna , BigDecimal valor ){
try {
ps.setBigDecimal(coluna, valor);
}catch(SQLException e){return false;}
return true;
}
public Object getObject(int coluna) throws SQLException {
return rs.getObject(coluna);
}
public int getInt(int coluna) throws SQLException {
return rs.getInt(coluna);
}
public double getDouble(int coluna) throws SQLException {
return rs.getDouble(coluna);
}
public long getLong(int coluna) throws SQLException {
return rs.getLong(coluna);
}
public String getString(int coluna) throws SQLException {
return rs.getString(coluna);
}
public float getFloat(int coluna) throws SQLException {
return rs.getFloat(coluna);
}
public BigDecimal getBigDecimal(int coluna) throws SQLException {
return rs.getBigDecimal(coluna);
}
}
package sicla.sgbd;
/*
*
* Modulo: TbUsuarios
* Descrição: Tabela de controle dos usuarios
*
* Created on 7 de Janeiro de 2003, 14:35
*/
/**
* @author William Jammes de Oliveira
*/
import java.sql.*;
import java.security.*;
public class TbUsuarios extends Tabela {
public int CODIGO = 0;
public int NOME = 1;
public int PASSWD = 2;
public int MODULO = 3;
public int ACESSO = 4;
private static final String[] SQLs={"SELECT * FROM TBUSUARIOS","INSERT INTO TBUSUARIOS (CODIGO, NOME, PASSWD, MODULO, ACESSO) VALUES (?,?,?,?,?)","UPDATE TBUSUARIOS SET CODIGO=?, SET NOME=?, PASSWD=?, MODULO=?, ACESSO=? WHERE CODIGO=?","DELETE FROM TBUSUARIOS WHERE CODIGO=?"};
private static final String TABELA = "TBUSUARIOS";
/** Creates a new instance of TbUsuarios */
public TbUsuarios() {
super(Database.getDataBase().getConn(),TABELA , SQLs);
PrimaryKey[] pKey = {new PrimaryKey(this.CODIGO)};
this.setPrimaryKey(pKey);
}
}
Parte desse codigo tirei da ideia de um amigo aqui do GUJ o resto foi doideira minha mesmo :d esqueci seu nick, mais ele sabe quem é !!!!
falow
Mas a pergunta é… ela é realmente interessante para o seu caso??? Algo parecido poderia ser utilizado quando você quer manter o código o mais independente possível de uma base de dados… mas se este não for o caso… acredito que muito disto poderia ser feito diretamente na base de dados… inclusive se estiver considerando performance ;)))
