01: /*
02: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
03: * (license2)
04: * Initial Developer: H2 Group
05: */
06: package org.h2.samples;
07:
08: import java.math.BigInteger;
09: import java.sql.Connection;
10: import java.sql.DriverManager;
11: import java.sql.ResultSet;
12: import java.sql.SQLException;
13: import java.sql.Statement;
14: import java.sql.Types;
15:
16: import org.h2.tools.SimpleResultSet;
17:
18: /**
19: * This sample application shows how to define and use
20: * custom (user defined) functions in this database.
21: */
22: public class Function {
23:
24: public static void main(String[] args) throws Exception {
25: Class.forName("org.h2.Driver");
26: Connection conn = DriverManager.getConnection("jdbc:h2:mem:",
27: "sa", "");
28: Statement stat = conn.createStatement();
29: stat
30: .execute("CREATE ALIAS IS_PRIME FOR \"org.h2.samples.Function.isPrime\" ");
31: ResultSet rs;
32: rs = stat
33: .executeQuery("SELECT IS_PRIME(X), X FROM SYSTEM_RANGE(1, 20) ORDER BY X");
34: while (rs.next()) {
35: boolean isPrime = rs.getBoolean(1);
36: if (isPrime) {
37: int x = rs.getInt(2);
38: System.out.println(x + " is prime");
39: }
40: }
41: conn.close();
42: }
43:
44: /**
45: * Check if a value is a prime number.
46: *
47: * @param value the value
48: * @return true if it is a prime number
49: */
50: public static boolean isPrime(int value) {
51: return new BigInteger(String.valueOf(value))
52: .isProbablePrime(100);
53: }
54:
55: /**
56: * Execute a query.
57: *
58: * @param conn the connection
59: * @param sql the SQL statement
60: * @return the result set
61: */
62: public static ResultSet query(Connection conn, String sql)
63: throws SQLException {
64: return conn.createStatement().executeQuery(sql);
65: }
66:
67: /**
68: * Creates a simple result set with one row.
69: *
70: * @return the result set
71: */
72: public static ResultSet simpleResultSet() throws SQLException {
73: SimpleResultSet rs = new SimpleResultSet();
74: rs.addColumn("ID", Types.INTEGER, 10, 0);
75: rs.addColumn("NAME", Types.VARCHAR, 255, 0);
76: rs.addRow(new Object[] { new Integer(0), "Hello" });
77: return rs;
78: }
79:
80: public static ResultSet getMatrix(Connection conn, Integer id)
81: throws SQLException {
82: SimpleResultSet rs = new SimpleResultSet();
83: rs.addColumn("X", Types.INTEGER, 10, 0);
84: rs.addColumn("Y", Types.INTEGER, 10, 0);
85: if (id == null) {
86: return rs;
87: }
88: for (int x = 0; x < id.intValue(); x++) {
89: for (int y = 0; y < id.intValue(); y++) {
90: rs
91: .addRow(new Object[] { new Integer(x),
92: new Integer(y) });
93: }
94: }
95: return rs;
96: }
97:
98: }
|