Debian Codegraph @

src/test/org/h2/samples/CachedPreparedStatements.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.samples;
7
8 import java.sql.Connection;
9 import java.sql.DriverManager;
10 import java.sql.PreparedStatement;
11 import java.sql.SQLException;
12 import java.sql.Statement;
13 import java.util.concurrent.ConcurrentHashMap;
14
15 /**
16 * This sample application shows how to cache prepared statements.
17 */
18 public class CachedPreparedStatements {
19
20 private Connection conn;
21 private Statement stat;
22 private final ConcurrentHashMap<String, PreparedStatement> prepared = new ConcurrentHashMap<>();
23
24 /**
25 * This method is called when executing this sample application from the
26 * command line.
27 *
28 * @param args the command line parameters
29 * @throws Exception on failure
30 */
31 public static void main(String... args) throws Exception {
32 new CachedPreparedStatements().run();
33 }
34
35 private void run() throws Exception {
36 Class.forName("org.h2.Driver");
37 conn = DriverManager.getConnection(
38 "jdbc:h2:mem:", "sa", "");
39 stat = conn.createStatement();
40 stat.execute(
41 "create table test(id int primary key, name varchar)");
42 PreparedStatement prep = prepare(
43 "insert into test values(?, ?)");
44 prep.setInt(1, 1);
45 prep.setString(2, "Hello");
46 prep.execute();
47 conn.close();
48 }
49
50 private PreparedStatement prepare(String sql)
51 throws SQLException {
52 PreparedStatement prep = prepared.get(sql);
53 if (prep == null) {
54 prep = conn.prepareStatement(sql);
55 prepared.put(sql, prep);
56 }
57 return prep;
58 }
59
60 }