0
# JDBC API
1
2
Phoenix Core provides a complete JDBC 4.0 implementation that enables standard SQL database connectivity to HBase. The JDBC API serves as the primary interface for client applications to interact with Phoenix.
3
4
## Core Imports
5
6
```java
7
import org.apache.phoenix.jdbc.*;
8
import java.sql.*;
9
import java.util.Properties;
10
```
11
12
## Driver Management
13
14
### PhoenixDriver
15
16
The main JDBC driver implementation for production use. Extends PhoenixEmbeddedDriver and provides connection pooling and caching.
17
18
```java{ .api }
19
public final class PhoenixDriver extends PhoenixEmbeddedDriver {
20
public static final PhoenixDriver INSTANCE;
21
22
// Standard JDBC Driver methods
23
public Connection connect(String url, Properties info) throws SQLException
24
public boolean acceptsURL(String url) throws SQLException
25
26
// Phoenix-specific methods
27
public QueryServices getQueryServices() throws SQLException
28
public void close() throws SQLException
29
void invalidateCache(String url, Properties properties) throws SQLException
30
}
31
```
32
33
**Usage:**
34
```java
35
// Driver is automatically registered via static initialization
36
String url = "jdbc:phoenix:zk1,zk2,zk3:2181";
37
Properties props = new Properties();
38
39
Connection connection = DriverManager.getConnection(url, props);
40
```
41
42
### PhoenixEmbeddedDriver
43
44
Abstract base driver class with embedded driver functionality.
45
46
```java{ .api }
47
public abstract class PhoenixEmbeddedDriver implements Driver, SQLCloseable {
48
public abstract QueryServices getQueryServices() throws SQLException
49
50
// Standard JDBC Driver methods
51
public boolean acceptsURL(String url) throws SQLException
52
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException
53
public int getMajorVersion()
54
public int getMinorVersion()
55
public boolean jdbcCompliant()
56
public Logger getParentLogger() throws SQLFeatureNotSupportedException
57
}
58
```
59
60
## Connection Management
61
62
### PhoenixConnection
63
64
Primary connection implementation providing Phoenix-specific extensions to standard JDBC Connection.
65
66
```java{ .api }
67
public class PhoenixConnection implements MetaDataMutated, SQLCloseable, PhoenixMonitoredConnection {
68
// Constructors
69
public PhoenixConnection(PhoenixConnection connection) throws SQLException
70
public PhoenixConnection(ConnectionQueryServices services, String url, Properties info, PMetaData metaData) throws SQLException
71
72
// Standard JDBC Connection methods
73
public Statement createStatement() throws SQLException
74
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException
75
public PreparedStatement prepareStatement(String sql) throws SQLException
76
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
77
public void commit() throws SQLException
78
public void rollback() throws SQLException
79
public void close() throws SQLException
80
public boolean getAutoCommit() throws SQLException
81
public void setAutoCommit(boolean autoCommit) throws SQLException
82
83
// Phoenix-specific extensions
84
public ConnectionQueryServices getQueryServices()
85
public PMetaData getMetaDataCache()
86
public MutationState getMutationState()
87
public PTable getTable(String name) throws SQLException
88
public PTable getTable(PTableKey key) throws SQLException
89
public PTable getTableNoCache(String name) throws SQLException
90
public @Nullable PName getTenantId()
91
public Long getSCN()
92
public String getURL()
93
public int getMutateBatchSize()
94
public long getMutateBatchSizeBytes()
95
public String getDatePattern()
96
public String getTimePattern()
97
public String getTimestampPattern()
98
public boolean isInternalConnection()
99
public int executeStatements(Reader reader, List<Object> binds, PrintStream out) throws IOException, SQLException
100
}
101
```
102
103
**Usage:**
104
```java
105
PhoenixConnection phoenixConn = connection.unwrap(PhoenixConnection.class);
106
107
// Access Phoenix-specific features
108
PTable table = phoenixConn.getTable("my_table");
109
MutationState mutations = phoenixConn.getMutationState();
110
PName tenantId = phoenixConn.getTenantId();
111
Long scn = phoenixConn.getSCN();
112
```
113
114
### Connection Utilities
115
116
#### ConnectionInfo
117
118
Abstract base class containing connection configuration and connection string information.
119
120
```java{ .api }
121
public abstract class ConnectionInfo {
122
// Static factory method
123
public static ConnectionInfo create(String url, ReadOnlyProps props, Properties info) throws SQLException
124
125
// Instance methods
126
public abstract String getUrl()
127
public abstract ReadOnlyProps asProps()
128
public abstract boolean isConnectionless()
129
public boolean isTestUrl()
130
public String getPrincipal()
131
public String getKeytab()
132
public User getUser()
133
public String getHaGroup()
134
}
135
```
136
137
## Statement Interfaces
138
139
### PhoenixStatement
140
141
Phoenix implementation of JDBC Statement with monitoring capabilities.
142
143
```java{ .api }
144
public class PhoenixStatement implements PhoenixMonitoredStatement, SQLCloseable {
145
// Constructor
146
public PhoenixStatement(PhoenixConnection connection)
147
148
// Standard JDBC Statement methods
149
public ResultSet executeQuery(String sql) throws SQLException
150
public int executeUpdate(String sql) throws SQLException
151
public boolean execute(String sql) throws SQLException
152
public void close() throws SQLException
153
public PhoenixConnection getConnection() throws SQLException
154
public int getMaxRows() throws SQLException
155
public void setMaxRows(int max) throws SQLException
156
public int getQueryTimeout() throws SQLException
157
public void setQueryTimeout(int seconds) throws SQLException
158
public void addBatch(String sql) throws SQLException
159
public void clearBatch() throws SQLException
160
public int[] executeBatch() throws SQLException
161
162
// Phoenix-specific methods
163
public PhoenixResultSet newResultSet(ResultIterator iterator, RowProjector projector, StatementContext context) throws SQLException
164
public String getTargetForAudit(CompilableStatement stmt)
165
}
166
```
167
168
**Usage:**
169
```java
170
PhoenixStatement stmt = connection.createStatement().unwrap(PhoenixStatement.class);
171
172
// Execute queries
173
String sql = "SELECT * FROM users WHERE age > 25";
174
ResultSet rs = stmt.executeQuery(sql);
175
176
// Execute updates
177
int rowsAffected = stmt.executeUpdate("DELETE FROM users WHERE status = 'INACTIVE'");
178
```
179
180
### PhoenixPreparedStatement
181
182
Phoenix implementation of JDBC PreparedStatement.
183
184
```java{ .api }
185
public class PhoenixPreparedStatement extends PhoenixStatement implements PhoenixMonitoredPreparedStatement, SQLCloseable {
186
// Constructors
187
public PhoenixPreparedStatement(PhoenixConnection connection, String query) throws SQLException
188
public PhoenixPreparedStatement(PhoenixConnection connection, PhoenixStatementParser parser) throws SQLException, IOException
189
190
// Standard JDBC PreparedStatement methods
191
public ResultSet executeQuery() throws SQLException
192
public int executeUpdate() throws SQLException
193
public boolean execute() throws SQLException
194
public void addBatch() throws SQLException
195
public void clearParameters() throws SQLException
196
197
// Parameter setting methods
198
public void setString(int parameterIndex, String x) throws SQLException
199
public void setInt(int parameterIndex, int x) throws SQLException
200
public void setLong(int parameterIndex, long x) throws SQLException
201
public void setDouble(int parameterIndex, double x) throws SQLException
202
public void setFloat(int parameterIndex, float x) throws SQLException
203
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException
204
public void setBoolean(int parameterIndex, boolean x) throws SQLException
205
public void setByte(int parameterIndex, byte x) throws SQLException
206
public void setShort(int parameterIndex, short x) throws SQLException
207
public void setBytes(int parameterIndex, byte[] x) throws SQLException
208
public void setDate(int parameterIndex, Date x) throws SQLException
209
public void setTime(int parameterIndex, Time x) throws SQLException
210
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException
211
public void setNull(int parameterIndex, int sqlType) throws SQLException
212
public void setObject(int parameterIndex, Object x) throws SQLException
213
214
// Metadata methods
215
public ResultSetMetaData getMetaData() throws SQLException
216
public ParameterMetaData getParameterMetaData() throws SQLException
217
218
// Phoenix-specific methods
219
public List<Object> getParameters()
220
public QueryPlan compileQuery() throws SQLException
221
public MutationPlan compileMutation() throws SQLException
222
public QueryPlan optimizeQuery() throws SQLException
223
}
224
```
225
226
**Usage:**
227
```java
228
String sql = "SELECT * FROM users WHERE id = ? AND status = ?";
229
PhoenixPreparedStatement pstmt = connection.prepareStatement(sql)
230
.unwrap(PhoenixPreparedStatement.class);
231
232
pstmt.setLong(1, userId);
233
pstmt.setString(2, "ACTIVE");
234
235
ResultSet rs = pstmt.executeQuery();
236
```
237
238
## Result Sets and Metadata
239
240
### PhoenixResultSet
241
242
Phoenix implementation of JDBC ResultSet with monitoring capabilities.
243
244
```java{ .api }
245
public class PhoenixResultSet implements PhoenixMonitoredResultSet, SQLCloseable {
246
// Constructor
247
public PhoenixResultSet(ResultIterator resultIterator, RowProjector rowProjector, StatementContext context) throws SQLException
248
249
// Standard JDBC ResultSet methods
250
public boolean next() throws SQLException
251
public boolean first() throws SQLException
252
public boolean last() throws SQLException
253
public void close() throws SQLException
254
public boolean isClosed() throws SQLException
255
256
// Data retrieval methods
257
public String getString(int columnIndex) throws SQLException
258
public String getString(String columnLabel) throws SQLException
259
public int getInt(int columnIndex) throws SQLException
260
public int getInt(String columnLabel) throws SQLException
261
public long getLong(int columnIndex) throws SQLException
262
public long getLong(String columnLabel) throws SQLException
263
public double getDouble(int columnIndex) throws SQLException
264
public double getDouble(String columnLabel) throws SQLException
265
public BigDecimal getBigDecimal(int columnIndex) throws SQLException
266
public BigDecimal getBigDecimal(String columnLabel) throws SQLException
267
public Date getDate(int columnIndex) throws SQLException
268
public Date getDate(String columnLabel) throws SQLException
269
public Time getTime(int columnIndex) throws SQLException
270
public Time getTime(String columnLabel) throws SQLException
271
public Timestamp getTimestamp(int columnIndex) throws SQLException
272
public Timestamp getTimestamp(String columnLabel) throws SQLException
273
public boolean getBoolean(int columnIndex) throws SQLException
274
public boolean getBoolean(String columnLabel) throws SQLException
275
public byte getByte(int columnIndex) throws SQLException
276
public byte getByte(String columnLabel) throws SQLException
277
public byte[] getBytes(int columnIndex) throws SQLException
278
public byte[] getBytes(String columnLabel) throws SQLException
279
public Object getObject(int columnIndex) throws SQLException
280
public Object getObject(String columnLabel) throws SQLException
281
public Array getArray(int columnIndex) throws SQLException
282
public Array getArray(String columnLabel) throws SQLException
283
284
// Metadata methods
285
public ResultSetMetaData getMetaData() throws SQLException
286
public int findColumn(String columnLabel) throws SQLException
287
288
// Navigation methods
289
public boolean wasNull() throws SQLException
290
public void clearWarnings() throws SQLException
291
public SQLWarning getWarnings() throws SQLException
292
}
293
```
294
295
**Usage:**
296
```java
297
ResultSet rs = stmt.executeQuery("SELECT id, name, created_date FROM users");
298
PhoenixResultSet phoenixRs = rs.unwrap(PhoenixResultSet.class);
299
300
while (rs.next()) {
301
long id = rs.getLong("id");
302
String name = rs.getString("name");
303
Date created = rs.getDate("created_date");
304
305
// Check for null values
306
if (rs.wasNull()) {
307
System.out.println("Last column was null");
308
}
309
}
310
```
311
312
### PhoenixResultSetMetaData
313
314
Metadata for Phoenix result sets.
315
316
```java{ .api }
317
public class PhoenixResultSetMetaData implements ResultSetMetaData {
318
public PhoenixResultSetMetaData(PhoenixConnection connection, RowProjector projector)
319
320
public int getColumnCount() throws SQLException
321
public String getColumnName(int column) throws SQLException
322
public String getColumnLabel(int column) throws SQLException
323
public int getColumnType(int column) throws SQLException
324
public String getColumnTypeName(int column) throws SQLException
325
public String getColumnClassName(int column) throws SQLException
326
public int getPrecision(int column) throws SQLException
327
public int getScale(int column) throws SQLException
328
public int getColumnDisplaySize(int column) throws SQLException
329
public int isNullable(int column) throws SQLException
330
public boolean isAutoIncrement(int column) throws SQLException
331
public boolean isCaseSensitive(int column) throws SQLException
332
public boolean isSearchable(int column) throws SQLException
333
public boolean isCurrency(int column) throws SQLException
334
public boolean isSigned(int column) throws SQLException
335
}
336
```
337
338
### PhoenixDatabaseMetaData
339
340
Phoenix implementation of JDBC DatabaseMetaData.
341
342
```java{ .api }
343
public class PhoenixDatabaseMetaData implements DatabaseMetaData {
344
public PhoenixDatabaseMetaData(PhoenixConnection connection) throws SQLException
345
346
public ResultSet getTables(String catalog, String schemaPattern,
347
String tableNamePattern, String[] types) throws SQLException
348
public ResultSet getColumns(String catalog, String schemaPattern,
349
String tableNamePattern, String columnNamePattern) throws SQLException
350
public ResultSet getIndexInfo(String catalog, String schema, String table,
351
boolean unique, boolean approximate) throws SQLException
352
public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException
353
public ResultSet getSchemas() throws SQLException
354
public ResultSet getSchemas(String catalog, String schemaPattern) throws SQLException
355
public ResultSet getCatalogs() throws SQLException
356
public ResultSet getTableTypes() throws SQLException
357
public String getDatabaseProductName() throws SQLException
358
public String getDatabaseProductVersion() throws SQLException
359
public String getDriverName() throws SQLException
360
public String getDriverVersion() throws SQLException
361
public int getDriverMajorVersion()
362
public int getDriverMinorVersion()
363
}
364
```
365
366
### PhoenixParameterMetaData
367
368
Parameter metadata for Phoenix prepared statements.
369
370
```java{ .api }
371
public class PhoenixParameterMetaData implements ParameterMetaData {
372
public PhoenixParameterMetaData(PhoenixConnection connection, PDatum[] params)
373
374
public int getParameterCount() throws SQLException
375
public int getParameterType(int param) throws SQLException
376
public String getParameterTypeName(int param) throws SQLException
377
public String getParameterClassName(int param) throws SQLException
378
public int getPrecision(int param) throws SQLException
379
public int getScale(int param) throws SQLException
380
public int isNullable(int param) throws SQLException
381
public boolean isSigned(int param) throws SQLException
382
}
383
```
384
385
**Usage:**
386
```java
387
// Database metadata
388
DatabaseMetaData metaData = connection.getMetaData();
389
ResultSet tables = metaData.getTables(null, "MYSCHEMA", "%", new String[]{"TABLE"});
390
391
// Parameter metadata for prepared statements
392
PreparedStatement pstmt = connection.prepareStatement("SELECT * FROM users WHERE id = ? AND age > ?");
393
ParameterMetaData paramMeta = pstmt.getParameterMetaData();
394
int paramCount = paramMeta.getParameterCount();
395
396
// Result set metadata
397
ResultSet rs = pstmt.executeQuery();
398
ResultSetMetaData rsMeta = rs.getMetaData();
399
int columnCount = rsMeta.getColumnCount();
400
```
401
402
## High Availability and Failover
403
404
### FailoverPhoenixConnection
405
406
Connection implementation with failover capabilities that wraps a regular PhoenixConnection and provides automatic failover between HBase clusters.
407
408
```java{ .api }
409
public class FailoverPhoenixConnection implements PhoenixMonitoredConnection {
410
// Constants
411
public static final String FAILOVER_TIMEOUT_MS_ATTR = "phoenix.ha.failover.timeout.ms"
412
public static final long FAILOVER_TIMEOUT_MS_DEFAULT = 10_000
413
414
// Constructor
415
public FailoverPhoenixConnection(HighAvailabilityGroup haGroup, Properties properties, FailoverPolicy policy) throws SQLException
416
417
// Standard JDBC Connection methods (delegated)
418
public Statement createStatement() throws SQLException
419
public PreparedStatement prepareStatement(String sql) throws SQLException
420
public void close() throws SQLException
421
public boolean isClosed() throws SQLException
422
public void commit() throws SQLException
423
public void rollback() throws SQLException
424
public boolean getAutoCommit() throws SQLException
425
public void setAutoCommit(boolean autoCommit) throws SQLException
426
public DatabaseMetaData getMetaData() throws SQLException
427
428
// High availability methods
429
public HighAvailabilityGroup getHighAvailabilityGroup()
430
public FailoverPolicy getFailoverPolicy()
431
public PhoenixConnection getWrappedConnection()
432
public boolean isFailoverNeeded() throws SQLException
433
}
434
```
435
436
### HighAvailabilityGroup
437
438
Manages high availability groups for Phoenix connections with cluster role monitoring.
439
440
```java{ .api }
441
public class HighAvailabilityGroup {
442
// Constants
443
public static final String PHOENIX_HA_ATTR_PREFIX = "phoenix.ha."
444
public static final String PHOENIX_HA_GROUP_ATTR = PHOENIX_HA_ATTR_PREFIX + "group.name"
445
public static final String PHOENIX_HA_ZOOKEEPER_ZNODE_NAMESPACE = "phoenix/ha"
446
447
// Static factory method
448
public static HighAvailabilityGroup create(String name, Properties props) throws SQLException
449
450
// Instance methods
451
public String getGroupName()
452
public ClusterRoleRecord getClusterRoleRecord(String cluster) throws SQLException
453
public Optional<String> getActiveClusterUrl() throws SQLException
454
public boolean isActive(String clusterUrl) throws SQLException
455
public void close() throws SQLException
456
public boolean isClosed()
457
}
458
```
459
460
### FailoverPolicy
461
462
Functional interface defining failover behavior policies.
463
464
```java{ .api }
465
@FunctionalInterface
466
public interface FailoverPolicy {
467
// Constants
468
String PHOENIX_HA_FAILOVER_POLICY_ATTR = "phoenix.ha.failover.policy"
469
String PHOENIX_HA_FAILOVER_COUNT_ATTR = "phoenix.ha.failover.count"
470
471
// Main method
472
boolean shouldFailover(FailoverSQLException exception, int failoverCount)
473
474
// Predefined policies
475
FailoverPolicy NEVER = (exception, count) -> false
476
FailoverPolicy IMMEDIATE = (exception, count) -> true
477
FailoverPolicy MAX_RETRIES = (exception, count) -> count < 3
478
}
479
```
480
481
**Usage:**
482
```java
483
// Set up connection properties for HA
484
Properties props = new Properties();
485
props.setProperty(HighAvailabilityGroup.PHOENIX_HA_GROUP_ATTR, "production-group");
486
props.setProperty(FailoverPolicy.PHOENIX_HA_FAILOVER_POLICY_ATTR, "immediate");
487
488
// Connect using HA-enabled URL
489
String url = "jdbc:phoenix+zk://cluster1-zk1:2181,cluster1-zk2:2181/hbase;" +
490
"phoenix.ha.group.name=production-group";
491
492
Connection connection = DriverManager.getConnection(url, props);
493
FailoverPhoenixConnection haConnection = connection.unwrap(FailoverPhoenixConnection.class);
494
495
// Check if failover is needed
496
if (haConnection.isFailoverNeeded()) {
497
LOG.info("Cluster failover detected, connection will handle automatically");
498
}
499
```
500
501
## Parallel Processing
502
503
### ParallelPhoenixConnection
504
505
Connection implementation supporting parallel query execution across multiple connections.
506
507
```java{ .api }
508
public class ParallelPhoenixConnection implements PhoenixMonitoredConnection {
509
// Constructor
510
public ParallelPhoenixConnection(List<String> urls, Properties properties) throws SQLException
511
512
// Standard JDBC Connection methods (delegated to primary connection)
513
public Statement createStatement() throws SQLException
514
public PreparedStatement prepareStatement(String sql) throws SQLException
515
public void close() throws SQLException
516
public boolean isClosed() throws SQLException
517
public void commit() throws SQLException
518
public void rollback() throws SQLException
519
520
// Parallel-specific methods
521
public List<PhoenixConnection> getAllConnections()
522
public PhoenixConnection getPrimaryConnection()
523
public int getConnectionCount()
524
public boolean isAllConnectionsClosed()
525
}
526
```
527
528
### ParallelPhoenixPreparedStatement
529
530
Prepared statement implementation for parallel query execution.
531
532
```java{ .api }
533
public class ParallelPhoenixPreparedStatement extends PhoenixPreparedStatement {
534
// Constructor
535
public ParallelPhoenixPreparedStatement(ParallelPhoenixConnection connection, String sql) throws SQLException
536
537
// All standard PreparedStatement methods are inherited
538
// Execution is automatically parallelized across multiple connections
539
}
540
```
541
542
**Usage:**
543
```java
544
// Create parallel connection with multiple cluster URLs
545
List<String> clusterUrls = Arrays.asList(
546
"jdbc:phoenix:zk1:2181",
547
"jdbc:phoenix:zk2:2181",
548
"jdbc:phoenix:zk3:2181"
549
);
550
551
Properties props = new Properties();
552
ParallelPhoenixConnection parallelConn = new ParallelPhoenixConnection(clusterUrls, props);
553
554
// Execute queries in parallel across clusters
555
PreparedStatement pstmt = parallelConn.prepareStatement("SELECT * FROM large_table WHERE id > ?");
556
pstmt.setLong(1, 1000000);
557
558
ResultSet rs = pstmt.executeQuery(); // Automatically parallelized
559
```
560
561
## Monitoring Interfaces
562
563
### PhoenixMonitoredConnection
564
565
Interface for monitored Phoenix connections that provides metrics collection.
566
567
```java{ .api }
568
public interface PhoenixMonitoredConnection extends Connection {
569
/**
570
* @return map of Table Name String to a Map of Metric Type to current value for mutations
571
*/
572
Map<String, Map<MetricType, Long>> getMutationMetrics()
573
574
/**
575
* @return map of Table Name String to a Map of Metric Type to current value for reads
576
*/
577
Map<String, Map<MetricType, Long>> getReadMetrics()
578
579
/**
580
* @return true if request metrics are enabled false otherwise
581
*/
582
boolean isRequestLevelMetricsEnabled()
583
584
/**
585
* Clears the local metrics values by setting them back to 0
586
*/
587
void clearMetrics()
588
}
589
```
590
591
### PhoenixMonitoredStatement
592
593
Interface for monitored Phoenix statements.
594
595
```java{ .api }
596
public interface PhoenixMonitoredStatement extends Statement {
597
// Inherits all Statement methods
598
// Implementations provide monitoring capabilities
599
}
600
```
601
602
### PhoenixMonitoredPreparedStatement
603
604
Interface for monitored Phoenix prepared statements.
605
606
```java{ .api }
607
public interface PhoenixMonitoredPreparedStatement extends PreparedStatement, PhoenixMonitoredStatement {
608
// Inherits all PreparedStatement and PhoenixMonitoredStatement methods
609
// Implementations provide monitoring capabilities for prepared statements
610
}
611
```
612
613
### PhoenixMonitoredResultSet
614
615
Interface for monitored Phoenix result sets.
616
617
```java{ .api }
618
public interface PhoenixMonitoredResultSet extends ResultSet {
619
// Inherits all ResultSet methods
620
// Implementations provide monitoring capabilities for result set operations
621
}
622
```
623
624
## Common Usage Patterns
625
626
### Basic Query Execution
627
628
```java
629
// Establish connection
630
Connection connection = DriverManager.getConnection("jdbc:phoenix:localhost:2181");
631
632
try {
633
// Create and execute statement
634
Statement stmt = connection.createStatement();
635
ResultSet rs = stmt.executeQuery("SELECT id, name FROM users WHERE status = 'ACTIVE'");
636
637
// Process results
638
while (rs.next()) {
639
long id = rs.getLong("id");
640
String name = rs.getString("name");
641
System.out.println("User: " + id + " - " + name);
642
}
643
} finally {
644
connection.close();
645
}
646
```
647
648
### Prepared Statement with Parameters
649
650
```java
651
String sql = "INSERT INTO users (id, name, email, created_date) VALUES (?, ?, ?, ?)";
652
PreparedStatement pstmt = connection.prepareStatement(sql);
653
654
pstmt.setLong(1, 1001L);
655
pstmt.setString(2, "John Doe");
656
pstmt.setString(3, "john@example.com");
657
pstmt.setDate(4, new Date(System.currentTimeMillis()));
658
659
int rowsAffected = pstmt.executeUpdate();
660
System.out.println("Inserted " + rowsAffected + " rows");
661
```
662
663
### Batch Operations
664
665
```java
666
String sql = "INSERT INTO metrics (timestamp, metric_name, value) VALUES (?, ?, ?)";
667
PreparedStatement pstmt = connection.prepareStatement(sql);
668
669
// Add multiple rows to batch
670
for (int i = 0; i < 1000; i++) {
671
pstmt.setLong(1, System.currentTimeMillis() + i);
672
pstmt.setString(2, "cpu_usage");
673
pstmt.setDouble(3, Math.random() * 100);
674
pstmt.addBatch();
675
}
676
677
// Execute batch
678
int[] results = pstmt.executeBatch();
679
System.out.println("Batch inserted " + results.length + " rows");
680
```
681
682
### Transaction Management
683
684
```java
685
connection.setAutoCommit(false);
686
687
try {
688
Statement stmt = connection.createStatement();
689
690
// Multiple operations in transaction
691
stmt.executeUpdate("INSERT INTO accounts (id, balance) VALUES (1, 1000)");
692
stmt.executeUpdate("INSERT INTO accounts (id, balance) VALUES (2, 2000)");
693
stmt.executeUpdate("UPDATE accounts SET balance = balance - 100 WHERE id = 1");
694
stmt.executeUpdate("UPDATE accounts SET balance = balance + 100 WHERE id = 2");
695
696
// Commit transaction
697
connection.commit();
698
} catch (SQLException e) {
699
// Rollback on error
700
connection.rollback();
701
throw e;
702
} finally {
703
connection.setAutoCommit(true);
704
}
705
```