Created
June 17, 2020 23:19
-
-
Save gregori/c1487a8a0e85873819cdf8ac2a63cd46 to your computer and use it in GitHub Desktop.
This file contains 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 exemplo; | |
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 class DatabaseAccess { | |
private final String connectionUrl = "jdbc:sqlserver://localhost;databaseName=ExemploBanco;user=exemplobanco;password=catolica123"; | |
private Connection conn = null; | |
private Connection getConnection() { | |
try { | |
if (conn == null || conn.isClosed()) { | |
conn = DriverManager.getConnection(connectionUrl); | |
} | |
} catch (SQLException ex) { | |
throw new RuntimeException("Erro conectando ao banco de dados", ex); | |
} | |
return conn; | |
} | |
public List<Pessoa> getAllPessoas() { | |
Connection conn = getConnection(); | |
Statement stmt = null; | |
ResultSet rs = null; | |
List<Pessoa> pessoas = new ArrayList<Pessoa>(); | |
try { | |
stmt = conn.createStatement(); | |
String SQL = "SELECT * FROM Pessoa"; // consulta de SELECT | |
rs = stmt.executeQuery(SQL); // executa o SELECT | |
while (rs.next()) { | |
Pessoa p = new Pessoa(); // cria um objeto de pessoa | |
p.setId(rs.getInt("id")); // insere id recuperado do banco na pessoa | |
p.setNome(rs.getString("nome")); // insere nome recuperado do banco na pessoa | |
p.setIdade(rs.getInt("idade")); // insere idade recuperada do banco na pessoa | |
pessoas.add(p); | |
} | |
} catch (SQLException e) { | |
throw new RuntimeException("Erro ao selecionar todas as pessoas", e); | |
} finally { | |
try { | |
if (rs != null) { rs.close(); } | |
if (stmt != null) { stmt.close(); } | |
if (conn != null) { conn.close(); } | |
} catch (SQLException e) { | |
throw new RuntimeException("Erro ao fechar recursos.", e); | |
} | |
} | |
return pessoas; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment