简体   繁体   English

如何使用java在MySQL中插入JSONObject?

[英]How to insert JSONObject inside MySQL using java?

I'm trying to insert a JSONObject that contains a couple of JSONArrays in it inside a MySQL database that I have.我正在尝试在我拥有的 MySQL 数据库中插入一个包含几个 JSONArrays 的 JSONObject。

This is what I'm currently trying to do:这就是我目前正在尝试做的事情:

JSONObject fiveMin = new JSONObject();
JSONArray data = new JSONArray();
data.add(45);

fiveMin.put("data", data);

String query = "UPDATE frame_data.all_frame_data" 
            + "SET 5_min_data = " + fiveMin
            + " WHERE stock_id = 1";

stmt.executeUpdate(query);

However, it's giving me a null pointer exception.但是,它给了我一个空指针异常。

Anyone know how to fix this?有人知道怎么修这个东西吗? I've been stuck on this for days我已经被困在这个问题上好几天了

your Query is not correct you need a space after frame_data.all_frame_data because this now look like frame_data.all_frame_dataSET 5_min_data , change your Query to be like this :您的查询不正确,您需要在frame_data.all_frame_data之后frame_data.all_frame_data一个空格,因为这现在看起来像frame_data.all_frame_dataSET 5_min_data ,请将您的查询更改为如下所示:

String query = "UPDATE frame_data.all_frame_data SET 5_min_data = " + fiveMin
            + " WHERE stock_id = 1";

Second i don't think that there are a type JSONObject in MySql so i think you are using a varchar or a text to store your data, so fiveMin should convert to a String and not set like you do for example :其次,我认为 MySql 中没有JSONObject ,因此我认为您正在使用 varchar 或文本来存储数据,因此fiveMin应该转换为 String 而不是像您那样设置,例如:

fiveMin.toString();

You query should look like this :您的查询应如下所示:

String query = "UPDATE frame_data.all_frame_data SET 5_min_data = '" + fiveMin.toString()
            + "' WHERE stock_id = 1";

I suggest to use PreparedStatement you can learn more here : PreparedStatement我建议使用 PreparedStatement 您可以在此处了解更多信息: PreparedStatement

Thank you.谢谢你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM