Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

java source for jdbc postgresql command-line demo

Project: Earth Science
Views: 316
1
import java.sql.DriverManager;
2
import java.sql.Connection;
3
import java.sql.SQLException;
4
import java.sql.Statement;
5
import java.sql.ResultSet;
6
7
public class JDBCExample {
8
9
public static void main(String[] argv) {
10
11
System.out.println("-------- PostgreSQL " +
12
"JDBC Connection Testing ------------");
13
14
try {
15
16
Class.forName("org.postgresql.Driver");
17
18
} catch (ClassNotFoundException e) {
19
20
System.out.println("Where is your PostgreSQL JDBC Driver? " +
21
"Include in your library path!");
22
e.printStackTrace();
23
return;
24
25
}
26
27
System.out.println("PostgreSQL JDBC Driver Registered.");
28
29
Connection connection = null;
30
Statement stmt = null;
31
32
try {
33
34
connection = DriverManager.getConnection(
35
"jdbc:postgresql://127.0.0.1:15432/test", "user",
36
"");
37
String sql = "SELECT * from people";
38
stmt = connection.createStatement();
39
ResultSet rs = stmt.executeQuery(sql);
40
//STEP 5: Extract data from result set
41
while (rs.next()) {
42
//Retrieve by column name
43
String name = rs.getString("name");
44
int age = rs.getInt("age");
45
46
//Display values
47
System.out.print("Age: " + age);
48
System.out.println(", Name: " + name);
49
}
50
rs.close();
51
52
} catch (SQLException e) {
53
54
System.out.println("Connection Failed. Check output console");
55
e.printStackTrace();
56
return;
57
58
}
59
60
if (connection != null) {
61
System.out.println("Connection test succeeded.");
62
} else {
63
System.out.println("Failed to make connection.");
64
}
65
}
66
67
}
68
69