包阅导读总结
1. 关键词:PostgreSQL、JSON、PreparedStatement、Java、数据存储
2. 总结:本文介绍了在 PostgreSQL 中使用 PreparedStatement 存储 JSON 数据的方法。包括 JSONB 和 JSON 类型的区别,在 Docker 上设置数据库,创建含 JSON 列的表,通过 Java 代码插入 JSON 数据,最后总结其高效便捷的特点。
3. 主要内容:
– 在 PostgreSQL 中存储 JSON 数据
– JSON 和 JSONB 类型对比
– JSON 存储输入的 JSON 文本,需每次查询时解析,较慢。
– JSONB 以二进制格式存储,支持索引,查询更快,多数情况推荐使用。
– 在 Docker 上设置数据库
– 相关命令及注意事项,如设置、停止和删除容器,自定义密码等。
– 创建含 JSON 列的 PostgreSQL 表
– 示例创建 `user_data` 表,包含自增主键 `id` 和 `JSONB` 类型的 `user_info` 列。
– 用 Java 代码插入 JSON 数据
– Maven 依赖
– 示例代码
– 建立连接,准备 JSON 数据。
– 转换数据,准备 SQL 语句。
– 设置参数,执行更新,处理异常和关闭资源。
– 结论
– 强调在 PostgreSQL 中用 Java 存储和查询 JSON 数据的高效和灵活性。
思维导图:
文章地址:https://www.javacodegeeks.com/insert-json-object-to-postgresql-using-preparedstatement.html
文章来源:javacodegeeks.com
作者:Yatin Batra
发布时间:2024/8/7 14:56
语言:英文
总字数:857字
预计阅读时间:4分钟
评分:87分
标签:PostgreSQL,JSONB,Java,预编译语句,Docker
以下为原文内容
本内容来源于用户推荐转载,旨在分享知识与观点,如有侵权请联系删除 联系邮箱 media@ilingban.com
Storing JSON data in a PostgreSQL database can be quite efficient and effective. PostgreSQL offers two data types to store JSON: JSON
and JSONB
. Let us delve into understanding the differences between these types, how to create a PostgreSQL table with a JSON column, and how to insert a JSON object using Java’s PreparedStatement.
1. JSONB vs. JSON Type
PostgreSQL provides two data types for storing JSON data: JSON
and JSONB
.
- JSON: This type stores the exact JSON text as input. It performs input validation to ensure that the JSON is valid but does not process or store the data in a binary format. Querying JSON data stored as
JSON
can be slower since it needs to be parsed every time it is queried. - JSONB: This type stores JSON data in a binary format. It parses the input JSON text and stores it in a decomposed binary format, which allows for faster querying.
JSONB
also supports indexing, which can significantly improve the performance of JSON queries.
For most use cases, JSONB
is recommended due to its performance advantages and support for indexing.
1.1 Setting up a database on Docker
Usually, setting up the database is a tedious step but with Docker, it is a simple process. You can watch the video available at this link to understand the Docker installation on Windows OS. Once done open the terminal and trigger the below command to set and run postgresql.
-- Remember to change the password –docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=your_password --name postgres postgres-- command to stop the Postgres docker container --docker stop postgres-- command to remove the Postgres docker container --docker rm postgres
Remember to enter the password of your choice. If everything goes well the postgresql database server will be up and running on a port number – 5432
and you can connect with the Dbeaver GUI tool for connecting to the server.
2. Creating A PostgreSQL Table With JSON Column
To store JSON data in PostgreSQL, you need to create a table with a column of type JSON
or JSONB
. Here is an example of how to create such a table:
CREATE TABLE user_data ( id SERIAL PRIMARY KEY, user_info JSONB);
This SQL command creates a table named user_data
with two columns: id
, which is an auto-incrementing primary key, and user_info
, which is of type JSONB
.
3. Writing Java Code To Insert JSON Data
3.1 Maven Dependencies
First, ensure you have the necessary dependencies in your pom.xml
if you are using Maven:
<dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.2.18</version></dependency><dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.11.3</version></dependency>
3.2 Java Code
Here is an example that inserts a JSON object into a PostgreSQL table using PreparedStatement
:
package jcg.example;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;import com.fasterxml.jackson.databind.ObjectMapper;public class InsertJsonData { private static final String URL = "jdbc:postgresql://localhost:5432/your_database"; private static final String USER = "your_username"; private static final String PASSWORD = "your_password"; public static void main(String[] args) { Connection conn = null; PreparedStatement pstmt = null; try { // Establish connection conn = DriverManager.getConnection(URL, USER, PASSWORD); // JSON data to be inserted String jsonString = "{ \"name\": \"John Doe\", \"age\": 30, \"city\": \"New York\" }"; // Convert JSON string to JSONB object using Jackson ObjectMapper objectMapper = new ObjectMapper(); Object jsonObject = objectMapper.readValue(jsonString, Object.class); // Prepare SQL statement String sql = "INSERT INTO user_data (user_info) VALUES (?::jsonb)"; pstmt = conn.prepareStatement(sql); // Set JSONB data pstmt.setObject(1, jsonObject.toString()); // Execute update pstmt.executeUpdate(); System.out.println("JSON data is inserted successfully."); } catch (Exception e) { e.printStackTrace(); } finally { // Close resources try { if (pstmt != null) { pstmt.close(); } if (conn != null) { conn.close(); } } catch (SQLException ex) { ex.printStackTrace(); } } }}
3.2.1 Explanation
In the above code:
- We first import the necessary libraries, including JDBC and Jackson for JSON processing.
- We define the database connection details (URL, USER, PASSWORD).
- We establish a connection to the PostgreSQL database using
DriverManager.getConnection()
. - We create a JSON string representing the data to be inserted.
- We use Jackson’s
ObjectMapper
to convert the JSON string into a JSON object. - We prepare an SQL
INSERT
statement with a placeholder for the JSON data. - We set the JSON object as the value for the placeholder using
pstmt.setObject()
. The?::jsonb
syntax is used to explicitly cast the string tojsonb
type. - We execute the statement to insert the JSON data into the database.
- Finally, we close the resources (PreparedStatement and Connection).
Make sure to replace “your_database”, “your_username”, and “your_password” with actual values corresponding to your PostgreSQL setup.
3.2.2 Output
Here is the output of the Java code when it runs successfully.
JSON data is inserted successfully.
After running the Java code the user_data
table will have a new row inserted with the JSON data.
SELECT * FROM user_data;
4. Conclusion
Storing JSON data in PostgreSQL using Java is straightforward and efficient. By leveraging PostgreSQL’s JSONB type and Java’s PreparedStatement, you can efficiently store and query JSON data. This approach allows for flexibility in data storage and retrieval, making it a powerful combination for modern applications.