3

I have created a table books in PostgreSql.

CREATE TABLE books ( id integer, data json );

My Json:

 { "name": "Book the First", "author": { "first_name": "Bob", "last_name": "White" } }

How can i insert json into Postgres via java code?

Priyadharsini
  • 101
  • 1
  • 4
  • Run an `insert` using a `PreparedStatement` –  Dec 08 '16 at 06:59
  • Hope this will be useful http://stackoverflow.com/questions/35844138/how-can-i-insert-json-object-into-postgres-using-java-preparedstatement – dkb Dec 08 '16 at 07:10

2 Answers2

6

Thank you :).This really helped me to resolve the issue.

String json = "{ \"name\": \"Book the First\", \"author\": { \"first_name\": \"Priya\", \"last_name\": \"White\" } }";
         PGobject jsonObject = new PGobject();
         jsonObject.setType("json");
         jsonObject.setValue(json);
         PreparedStatement stmt=c.prepareStatement("insert into books values(2,?)");
         stmt.setObject(1, jsonObject);
Priyadharsini
  • 101
  • 1
  • 4
0

I have another one doubt.How to split JSON key value pair and insert into postgreSql table's column.

For example my JSON looks like { "Name":"xyz" "salary":10000 }

I want to insert into separate columns Name and salary in Postgres.

Priyadharsini
  • 101
  • 1
  • 4