1 5 package org.h2.samples; 6 7 import java.math.BigInteger ; 8 import java.sql.Connection ; 9 import java.sql.DriverManager ; 10 import java.sql.ResultSet ; 11 import java.sql.SQLException ; 12 import java.sql.Statement ; 13 import java.sql.Types ; 14 15 import org.h2.tools.SimpleResultSet; 16 17 public class Function { 18 19 public static void main(String [] args) throws Exception { 20 Class.forName("org.h2.Driver"); 21 Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", ""); 22 Statement stat = conn.createStatement(); 23 stat.execute("CREATE ALIAS ISPRIME FOR \"org.h2.samples.Function.isPrime\" "); 24 ResultSet rs; 25 rs = stat.executeQuery("SELECT ISPRIME(X), X FROM SYSTEM_RANGE(1, 20) ORDER BY X"); 26 while(rs.next()) { 27 boolean isPrime = rs.getBoolean(1); 28 if(isPrime) { 29 int x = rs.getInt(2); 30 System.out.println(x + " is prime"); 31 } 32 } 33 conn.close(); 34 } 35 36 public static boolean isPrime(int value) { 37 return new BigInteger (String.valueOf(value)).isProbablePrime(100); 38 } 39 40 public static ResultSet query(Connection conn, String sql) throws SQLException { 41 return conn.createStatement().executeQuery(sql); 42 } 43 44 public static ResultSet simpleResultSet() throws SQLException { 45 SimpleResultSet rs = new SimpleResultSet(); 46 rs.addColumn("ID", Types.INTEGER, 10, 0); 47 rs.addColumn("NAME", Types.VARCHAR, 255, 0); 48 rs.addRow(new Object [] { new Integer (0), "Hello" }); 49 return rs; 50 } 51 52 public static ResultSet getMatrix(Connection conn, Integer id) throws SQLException { 53 SimpleResultSet rs = new SimpleResultSet(); 54 rs.addColumn("X", Types.INTEGER, 10, 0); 55 rs.addColumn("Y", Types.INTEGER, 10, 0); 56 if(id == null) { 57 return rs; 58 } 59 for(int x = 0; x < id.intValue(); x++) { 60 for(int y = 0; y < id.intValue(); y++) { 61 rs.addRow(new Object [] { new Integer (x), new Integer (y) }); 62 } 63 } 64 return rs; 65 } 66 67 } 68 | Popular Tags |