Last active
August 29, 2015 14:21
-
-
Save brunocarvalhodearaujo/e24dd5ddc2ceb6d731eb to your computer and use it in GitHub Desktop.
Desenvolvimento de Sistemas WEB (CCT0051) -- Rafael Monteiro | REF.: http://monteiror2m.blogspot.com.br/2015/05/jdbc.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Model; | |
import java.sql.*; | |
import java.util.ArrayList; | |
/** | |
* DATA ACCESS OBJECT (Objeto de Acesso a Arquivo) | |
* classe prove acesso simplificado ao banco de dados | |
* e retorna um Objetct[][] (array) ou uma excessão | |
* caso não consiga executar a operação | |
* @author Bruno Carvalho de Araujo | |
* @version 0.0.1 | |
*/ | |
public final class DAO { | |
/** | |
* dados de acesso a base de dados | |
*/ | |
private final String[] config = { | |
"localhost", // endereço do banco de dados | |
"exemplo", //> nome da tabela | |
"root", //> nome do usuario | |
"root" //> senha do usuario | |
}; | |
/** | |
* recupera uma instância do objeto de acesso | |
* ao banco de dados MySQL | |
* @return | |
* @throws Exception | |
*/ | |
private Connection getConnection() throws Exception { | |
try { | |
Class.forName("org.gjt.mm.mysql.Driver"); | |
return DriverManager.getConnection( | |
"jdbc:mysql://" + this.config[0] + "/" + this.config[1], this.config[2], this.config[3]); | |
} catch (SQLException error) { | |
throw new Exception(error); | |
} | |
} | |
/** | |
* executa a operação no banco de dados, caso ocorra com sucesso | |
* retorna um Object[][], caso a operação não seja um select o retorno | |
* estará vazio caso ocorra com sucesso, se ocorrer algum erro ele retorna | |
* uma exceção que poderá ser tratada posteriormente | |
* @param query String SQL query a ser executada | |
* @param values String[] valores para o preparedStatement | |
* @return Object[][] | |
* @throws Exception | |
*/ | |
public Object[][] execute(String query, String[] values) throws Exception { | |
try { | |
Connection connection = this.getConnection(); | |
PreparedStatement statement; | |
statement = connection.prepareStatement(query); | |
if (values != null) { | |
for (int x = 0; x < values.length; x++) { | |
statement.setString(x + 1, values[x]); | |
} | |
if (statement.execute() == true) | |
throw new Exception("error on run query"); | |
} else { | |
ResultSet rs = statement.executeQuery(); | |
ResultSetMetaData rsMetaData = rs.getMetaData(); | |
int columnCount = rsMetaData.getColumnCount(); | |
ArrayList<Object[]> result = new ArrayList<Object[]>(); | |
Object[] header = new Object[columnCount]; | |
for (int i = 1; i <= columnCount; ++i) { | |
Object label = rsMetaData.getColumnLabel(i); | |
header[i - 1] = label; | |
} | |
while (rs.next()) { | |
Object[] str = new Object[columnCount]; | |
for (int i = 1; i <= columnCount; ++i) { | |
Object obj = rs.getObject(i); | |
str[i - 1] = obj; | |
} | |
result.add(str); | |
} | |
int resultLength = result.size(); | |
Object[][] finalResult = new Object[resultLength + 1][columnCount]; | |
finalResult[0] = header; | |
for (int i = 1; i < resultLength + 1; ++i) { | |
Object[] row = result.get(i - 1); | |
finalResult[i] = row; | |
} | |
statement.close(); | |
connection.close(); | |
return finalResult; | |
} | |
return null; | |
} catch (Exception error) { | |
throw new Exception(error); | |
} | |
} | |
/** | |
* retorna o total de itens em uma tabela | |
* @param table String nome da tabela | |
* @return int total | |
*/ | |
public int count(String table){ | |
try { | |
Object[][] resultado = this.execute("SELECT COUNT(*) FROM " + table, null); | |
String total = resultado[1][0].toString(); | |
return Integer.parseInt(total); | |
} catch (Exception error){ | |
return 0; | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%-- | |
Document : listaUsuario | |
Created on : 22/05/2015, 23:22:55 | |
Author : [email protected] | |
--%> | |
<%@page import="Model.User"%> | |
<%@page contentType="text/html" pageEncoding="UTF-8"%> | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> | |
<title>Listagem de Usúarios</title> | |
</head> | |
<body> | |
<% | |
/** | |
* OBS: deveria estar em um controller mais a ideia era so um exemplo, | |
* então coloquei direto no JSP, ah lembrando que linha 0 do array e o | |
* nome dos parametros, no caso o code, email, password, name, lastname | |
*/ | |
User u = new User(); | |
Object[][] resultado = u.findByEmail(null); | |
// percorre os usuarios | |
for (int x=0; x<resultado.length; x++){ | |
// percorre os dados do usuario | |
for (int y=0; y<resultado[x].length; y++){ | |
// exibe os dados do usuario | |
out.println(resultado[x][y]); | |
} | |
} | |
%> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- cria a tabela do usuario | |
CREATE TABLE IF NOT EXISTS `user` ( | |
`code` INT SERIAL NOT NULL, | |
`email` varchar(50) NOT NULL UNIQUE KEY, | |
`password` varchar(50), | |
`name` varchar(30), | |
`lastname` varchar(50) | |
); | |
-- insere um usúario de exemplo | |
INSERT INTO `user` (email, password, name, lastname) VALUES ('[email protected]', '123456789', 'usuario', 'exemplo'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Model; | |
/** | |
* Responsável por executar as operações CRUD | |
* na tabela User | |
* @author Bruno Carvalho de Araujo | |
* @table User | |
*/ | |
public class User { | |
/** | |
* objeto de acesso e manipulação direta a base de dados MySQL | |
*/ | |
private DAO DAO = new DAO(); | |
/** | |
* @return total de itens na tabela | |
*/ | |
protected int total(){ | |
return this.DAO.count("user"); | |
} | |
/** | |
* busca um usuario apartir de seu email, caso esteja nulo | |
* o parametro o sistema retornara todos os Usuarios cadastrados | |
* @param email Email do usúario, aceita ser nulo | |
* @return status da transação | |
*/ | |
protected Object[][] findByEmail(String email){ | |
try { | |
String query = "SELECT * FROM `user`"; | |
if (email != null) query += " WHERE code = '" + email +"'"; | |
return this.DAO.execute(query, null); | |
} catch (Exception error){ | |
return null; | |
} | |
} | |
/** | |
* persiste um novo usuario no banco de dados, | |
* todos os parametros são obrigatorios. | |
* @return status da transação | |
*/ | |
protected boolean create(String email, String password, String name, String lastname) { | |
try { | |
String query = "INSERT INTO user (`email`, `password`, `name`, `lastname`) VALUES (?,?,?,?)"; | |
String[] values = {email, password, name, lastname}; | |
this.DAO.execute(query, values); | |
return true; | |
} catch (Exception error){ | |
return false; | |
} | |
} | |
/** | |
* elimina um Usúario da base de dados. | |
* @param codigo | |
* @return | |
*/ | |
protected boolean remove(int codigo) { | |
try { | |
String query = "DELETE FROM user WHERE code = ?"; | |
String[] values = {Integer.toString(codigo)}; | |
this.DAO.execute(query, values); | |
return true; | |
} catch (Exception error){ | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment