Make json format insert in mysql and recover in Java [closed]

2

I have the following String in the format json :

{
  "ADT":"0",
  "CHD":"0",
  "INF":"0"
}

I need to insert in a table in mysql database and retrieve this in Java . I'm using VARCHAR (50) and looks like this:

{
"ADT":"0",
"CHD":"0",
"INF":"0"

I saw that in Mysql it has the type of field called Blob , used for binaries, but I did not understand how to recover it in Java .

    
asked by anonymous 09.09.2014 / 17:45

2 answers

0

If JSON has only these three properties, it might be best to persist as text. Anyway, Java has an object to work with Blob :

Entering:

String jsonString = "{'ADT':'0','CHD':'0','INF':'0'}";

Blob blob = con.createBlob(); // 'con' = um objeto de conexão criado anteriormente
blob.setBytes(1, jsonString.getBytes());

PreparedStatement pstm = con.prepareStatement("INSERT INTO foo VALUES(?)");
pstm.setBlob(1, blob);


Recovering:

Blob blob = rs.getBlob("data"); // 'rs' = algum ResultSet criado anteriormente
byte[] blobBytes = blob.getBytes(1, (int) blob.length());
String jsonString = new String(blobBytes);
    
19.01.2015 / 07:14
0

Fields of type BLOB we use to save files as image, documents, etc. If you want a large text field use CLOB.

Watch out for CLOB because it's a very heavy field and can hurt you on queries that bring too many records from this table. I've had problems with CLOB in database copies, in dumps, avoid if you can.

If it's a small JSON saved as text itself! (Mysql is varchar? I do not remember ...)

If you want to transform JSON into an object when you get back with it from the database, use Google's GSON.

Hugs

    
03.05.2015 / 07:15