-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample137.java
More file actions
53 lines (45 loc) · 1.71 KB
/
Example137.java
File metadata and controls
53 lines (45 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Example 137 from page 109
//
import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
class Example137 {
public static void main(String[] args) throws SQLException {
String url = "jdbc:postgresql://localhost/messages";
String usr = "nobody";
String pwd = "";
System.out.println("To run this example you need a data base server, a");
System.out.println("database, and a suitable JDBC driver.");
try { Class.forName("postgresql.Driver"); }
catch (ClassNotFoundException e)
{ System.out.println("Cannot find the Postgresql driver"); }
Connection conn = DriverManager.getConnection(url, usr, pwd);
printNameAndMsg(getRows(conn, "select * from message"));
}
// Return the query result as an ArrayList of Map from String to Object
static ArrayList<Map<String,Object>> getRows(Connection conn, String query)
throws SQLException
{
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(query);
ResultSetMetaData rsmd = rset.getMetaData();
int columncount = rsmd.getColumnCount();
ArrayList<Map<String,Object>> queryResult
= new ArrayList<Map<String,Object>>();
while (rset.next()) {
Map<String,Object> row = new HashMap<String,Object>();
for (int i=1; i<=columncount; i++)
row.put(rsmd.getColumnName(i), rset.getObject(i));
queryResult.add(row);
}
return queryResult;
}
static void printNameAndMsg(Collection<Map<String,Object>> coll) {
for (Map<String,Object> row : coll)
System.out.println(row.get("name") + ": " + row.get("msg"));
}
}