Advertisement
Guest User

Untitled

a guest
Feb 18th, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. import java.sql.Array;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.PreparedStatement;
  5. import java.sql.ResultSet;
  6. import java.sql.Statement;
  7.  
  8. /**
  9. *
  10. */
  11. public class JdbcArrayTest {
  12.  
  13. /**
  14. * Prepared statements in postgres jdbc have a bug when caching text[] array types.
  15. * They return null after the 5th call.
  16. */
  17. public static void testArrays(Connection c) throws Exception {
  18. try (Statement st = c.createStatement()) {
  19. st.execute("CREATE TABLE IF NOT EXISTS article (id serial, para text[], words int[])");
  20. st.execute("TRUNCATE article");
  21. }
  22.  
  23. try (PreparedStatement ps = c.prepareStatement("insert into article (id, para, words) values (?, ?, ?)");) {
  24. String[] para = {"Gimme danger, little stranger", "And I feel you at ease",
  25. "Gimme danger, little stranger", "And I feel your disease",
  26. "There's nothing in my dreams", "Just some ugly memories", "Kiss me like the ocean breeze, hey"};
  27. Integer[] words = {4,6,4,5,5,4,7};
  28. for (int id = 0; id < 20; id++) {
  29. Array array = c.createArrayOf("text", para);
  30. Array arrayInt = c.createArrayOf("int", words);
  31. ps.setInt(1, id);
  32. ps.setArray(2, array);
  33. ps.setArray(3, arrayInt);
  34. ps.execute();
  35. }
  36. }
  37.  
  38. try (PreparedStatement ps = c.prepareStatement("select para, words from article where id=?");) {
  39. for (int id = 0; id < 10; id++) {
  40. ps.setInt(1, id);
  41. ps.execute();
  42.  
  43. ResultSet rs = ps.getResultSet();
  44. rs.next();
  45. System.out.println(rs.getString(1));
  46. System.out.println(rs.getString(2));
  47. rs.close();
  48. }
  49. }
  50. }
  51.  
  52. public static void main (String[] args) throws Exception {
  53. try (Connection c = DriverManager.getConnection("jdbc:postgresql://localhost/jdbctest", "postgres", "pogo")) {
  54. testArrays(c);
  55. }
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement