/
JDBCRowSetTest.java
103 lines (76 loc) · 3.3 KB
/
JDBCRowSetTest.java
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package com.example.demo.RowSet;
import com.example.demo.RowSetUtil;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetFactory;
import java.sql.SQLException;
public class JDBCRowSetTest {
public static void main(String[] args) {
RowSetFactory factory = RowSetUtil.getRowSetFactory();
readFromPersonTable(factory);
updatePersonTable(factory);
}
private static void updatePersonTable(RowSetFactory factory) {
// Use try-with-resources block
try (JdbcRowSet jdbcRowSet = factory.createJdbcRowSet()) {
// Set the connection parameters
RowSetUtil.setConnectionParameters(jdbcRowSet);
// Set the auto-commit mode to false
jdbcRowSet.setAutoCommit(false);
// Set the command and input parameters
String sqlCommand = "SELECT person_id, first_name, last_name, income " +
"FROM person " +
"WHERE person_id = ?";
// Set the command to the RowSet object
jdbcRowSet.setCommand(sqlCommand);
jdbcRowSet.setInt(1, 5);
// Retrieve the data
jdbcRowSet.execute();
// If a row is retrieved, update it's income.
// Note the updateDouble, updateRow, commit methods being used.
if (jdbcRowSet.next()) {
double oldIncome = jdbcRowSet.getDouble("income");
double newIncome = oldIncome + 1000;
jdbcRowSet.updateDouble("income", newIncome);
jdbcRowSet.updateRow();
jdbcRowSet.commit();
}
// Print the records in the rowset
RowSetUtil.printPersonRecord(jdbcRowSet);
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void readFromPersonTable(RowSetFactory factory) {
// Use try-with-resources block
try (JdbcRowSet jdbcRowSet = factory.createJdbcRowSet()) {
// Set the connection parameters
RowSetUtil.setConnectionParameters(jdbcRowSet);
// Set the command and input parameters
String sqlCommand = "SELECT person_id, first_name, " +
"last_name FROM person " +
"WHERE person_id BETWEEN ? AND ?";
// Set the command to the RowSet object
jdbcRowSet.setCommand(sqlCommand);
jdbcRowSet.setInt(1, 1);
jdbcRowSet.setInt(2, 5);
// Retrieve the data
jdbcRowSet.execute();
// Scroll to the last row to get the row count.
// It may throw an exception if the underlying JdbcRowSet implementation
// does not support a bi-directional scrolling result set.
try {
jdbcRowSet.last();
System.out.println("Row Count: " + jdbcRowSet.getRow());
// Position the cursor before the first row
jdbcRowSet.beforeFirst();
}
catch(SQLException e) {
System.out.println("JdbcRowSet implementation supports forward-only scrolling");
}
// Print the records in the rowset
RowSetUtil.printPersonRecord(jdbcRowSet);
} catch (SQLException e) {
e.printStackTrace();
}
}
}