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 6566fe6

Browse files
Refatora código de consulta de estados
1 parent d32c7aa commit 6566fe6

File tree

1 file changed

+17
-11
lines changed

1 file changed

+17
-11
lines changed

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

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import java.sql.DriverManager;
44
import java.sql.SQLException;
5+
import java.sql.Statement;
56

67
public class App {
78
public static void main(String[] args){
@@ -14,18 +15,23 @@ public static void listarEstados() {
1415
System.out.println("Listando estados cadastrados no banco de dados");
1516
try {
1617
Class.forName("org.postgresql.Driver");
17-
try(var conn = DriverManager.getConnection("jdbc:postgresql://localhost/postgres", "gitpod", "")){
18-
var stm = conn.createStatement();
19-
var result = stm.executeQuery("select * from estado");
20-
while(result.next()) {
21-
System.out.println(result.getString("nome"));
22-
}
23-
}
2418
} catch (ClassNotFoundException e) {
25-
System.out.println("Não foi possível carregar o driver JDBC para acesso ao banco de dados: " + e.getMessage());
26-
} catch (SQLException e) {
27-
System.out.println("Não foi executar a consulta ao banco de dados: " + e.getMessage());
19+
System.err.println("Não foi possível carregar a biblioteca para acesso ao banco de dados: " + e.getMessage());
2820
}
29-
}
21+
22+
Statement statement = null;
23+
try(var conn = DriverManager.getConnection("jdbc:postgresql://localhost/postgres", "gitpod", "")){
24+
System.out.println("Conexão com o banco realizada com sucesso.");
25+
26+
statement = conn.createStatement();
27+
var result = statement.executeQuery("select * from estado");
28+
while(result.next()){
29+
System.out.printf("Id: %d Nome: %s UF: %s\n", result.getInt("id"), result.getString("nome"), result.getString("uf"));
30+
}
31+
} 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+
} }
3036

3137
}

0 commit comments

Comments
(0)

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