Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 267cb61

Browse files
Adiciona novos métodos de acesso ao banco no App.java
- Cria método para buscar estado pelo UF - Cria método para listar dados de qualquer tabela
1 parent 285ca4a commit 267cb61

File tree

1 file changed

+78
-17
lines changed

1 file changed

+78
-17
lines changed

‎src/main/java/com/example/App.java

Lines changed: 78 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,98 @@
11
package com.example;
22

3+
import java.sql.Connection;
34
import java.sql.DriverManager;
45
import java.sql.SQLException;
5-
import java.sql.Statement;
66

77
public class App {
8-
public static void main(String[] args){
9-
System.out.println();
10-
System.out.println("Aplicação Java de Exemplo\n");
11-
listarEstados();
8+
private static final String PASSWORD = "";
9+
private static final String USERNAME = "gitpod";
10+
private static final String JDBC_URL = "jdbc:postgresql://localhost/postgres";
11+
12+
public static void main(String[] args) {
13+
new App();
14+
}
15+
16+
public App(){
17+
try(var conn = getConnection()){
18+
carregarDriverJDBC();
19+
listarEstados(conn);
20+
localizarEstado(conn, "PR");
21+
listarDadosTabela(conn, "produto");
22+
} catch (SQLException e) {
23+
System.err.println("Não foi possível conectar ao banco de dados: " + e.getMessage());
24+
}
1225
}
1326

14-
public static void listarEstados() {
15-
System.out.println("Listando estados cadastrados no banco de dados");
27+
private void listarDadosTabela(Connection conn, String tabela) {
28+
var sql = "select * from " + tabela;
29+
//System.out.println(sql);
1630
try {
17-
Class.forName("org.postgresql.Driver");
18-
} catch (ClassNotFoundException e) {
19-
System.err.println("Não foi possível carregar a biblioteca para acesso ao banco de dados: " + e.getMessage());
31+
var statement = conn.createStatement();
32+
var result = statement.executeQuery(sql);
33+
34+
var metadata = result.getMetaData();
35+
int cols = metadata.getColumnCount();
36+
37+
for (int i = 1; i <= cols; i++) {
38+
System.out.printf("%-25s | ", metadata.getColumnName(i));
39+
}
40+
System.out.println();
41+
42+
while(result.next()){
43+
for (int i = 1; i <= cols; i++) {
44+
System.out.printf("%-25s | ", result.getString(i));
45+
}
46+
System.out.println();
47+
}
48+
} catch (SQLException e) {
49+
System.err.println("Erro na execução da consulta: " + e.getMessage());
50+
}
51+
52+
}
53+
54+
private void localizarEstado(Connection conn, String uf) {
55+
try{
56+
//var sql = "select * from estado where uf = '" + uf + "'"; //suscetível a SQL Injection
57+
var sql = "select * from estado where uf = ?";
58+
var statement = conn.prepareStatement(sql);
59+
//System.out.println(sql);
60+
statement.setString(1, uf);
61+
var result = statement.executeQuery();
62+
if(result.next()){
63+
System.out.printf("Id: %d Nome: %s UF: %s\n", result.getInt("id"), result.getString("nome"), result.getString("uf"));
64+
}
65+
System.out.println();
66+
} catch(SQLException e){
67+
System.err.println("Erro ao executar consulta SQL: " + e.getMessage());
2068
}
69+
70+
}
2171

22-
Statementstatement = null;
23-
try(varconn = DriverManager.getConnection("jdbc:postgresql://localhost/postgres", "gitpod", "")){
72+
privatevoidlistarEstados(Connectionconn) {
73+
try{
2474
System.out.println("Conexão com o banco realizada com sucesso.");
2575

26-
statement = conn.createStatement();
76+
varstatement = conn.createStatement();
2777
var result = statement.executeQuery("select * from estado");
2878
while(result.next()){
2979
System.out.printf("Id: %d Nome: %s UF: %s\n", result.getInt("id"), result.getString("nome"), result.getString("uf"));
3080
}
81+
System.out.println();
3182
} catch (SQLException e) {
32-
if(statement == null)
33-
System.err.println("Não foi possível conectar ao banco de dados: " + e.getMessage());
34-
else System.err.println("Não foi possível executar a consulta ao banco: " + e.getMessage());
35-
}
83+
System.err.println("Não foi possível executar a consulta ao banco: " + e.getMessage());
84+
}
85+
}
86+
87+
private Connection getConnection() throws SQLException {
88+
return DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
89+
}
90+
91+
private void carregarDriverJDBC() {
92+
try {
93+
Class.forName("org.postgresql.Driver");
94+
} catch (ClassNotFoundException e) {
95+
System.err.println("Não foi possível carregar a biblioteca para acesso ao banco de dados: " + e.getMessage());
96+
}
3697
}
3798
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /