Как оказалось, все довольно просто - без лишних слов привожу пример кода
public static void main(String[] args) { try { TestJson(); } catch (SQLException e) { System.out.println("-- Error"); e.printStackTrace(); } } public static void TestJson() throws SQLException { Connection c; Statement stmt; try { try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { System.out.println("А где ваш PostgreSQL JDBC драйвер? Включите в ваш library path!"); return; } c = DriverManager .getConnection("jdbc:postgresql://localhost:5432/testdatabase", "postgres", "password"); c.setAutoCommit(false); System.out.println("-- Opened database successfully"); String sql; //-------------- CREATE TABLE --------------- stmt = c.createStatement(); sql = "CREATE TABLE SAMPLE (ID INT PRIMARY KEY NOT NULL, DATA JSON)"; stmt.executeUpdate(sql); stmt.close(); System.out.println("-- Table created successfully"); //--------------- INSERT ROW with JSON v1 ------------------ stmt = c.createStatement(); sql = "INSERT INTO SAMPLE (ID,DATA) VALUES (1, '{\"username\":\"alena\",\"post\":1024,\"email\":\"butakova.alena@gmail.com\" , \"blocked\":true }' );"; stmt.executeUpdate(sql); //--------------- INSERT ROW with JSON v2 ------------------ int id = 2; String jsonString = "{\"username\":\"igor\",\"posts\":2048,\"email\":\"igor.butakov@gmail.com\"}"; PGobject jsonObject = new PGobject(); jsonObject.setType("json"); jsonObject.setValue(jsonString); PreparedStatement pstmt = c.prepareStatement("insert into sample (id, data) values (?, ?)"); pstmt.setInt(1, id); pstmt.setObject(2, jsonObject); pstmt.executeUpdate(); pstmt.close(); c.commit(); //--------------- SELECT DATA ------------------ //http://www.postgresql.org/docs/9.3/static/functions-json.html //http://www.postgresql.org/docs/9.4/static/functions-json.html stmt = c.createStatement(); ResultSet rs = stmt.executeQuery( "SELECT id, DATA, DATA::json->>'username' AS name FROM SAMPLE where DATA::json->>'blocked'='true' ;" ); while ( rs.next() ) { int objectid = rs.getInt("id"); String obj = rs.getString("data"); String name = rs.getString("name"); System.out.println(String.format("ID=%s, DATA=%s, NAME=%s",objectid,obj, name)); } rs.close(); stmt.close(); System.out.println("-- Operation SELECT done successfully"); c.close(); } catch (Exception e) { e.printStackTrace(); System.err.println(e.getClass().getName()+": "+e.getMessage()); System.exit(0); } System.out.println("-- All Operations done successfully"); }
соответственно после запуска будет выведено
и в базе данных появится табличка с данными
Комментариев нет:
Отправить комментарий