如何使用Java程序向PostgreSQL插入JSON数据并修正现有失效代码
问题原因
你现有代码存在4个核心错误:
- 直接把Java变量名
MESSAGE写进SQL字符串是无效的,SQL语句无法识别Java侧的变量 - PostgreSQL的
::是类型转换运算符,你的用法不符合语法规范 - 直接拼接JSON字符串到SQL容易触发注入问题、特殊字符转义错误,必须使用
PreparedStatement做参数绑定 - 若你的数据库连接未开启自动提交,插入后没有执行
commit操作,数据不会持久化到表中
修正后可运行代码
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class InsertJsonToPg { public static void main(String[] args) { Connection c = null; PreparedStatement pstmt = null; try { // 1. 建立数据库连接,替换成你自己的PG连接信息 Class.forName("org.postgresql.Driver"); c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/你的数据库名", "你的用户名", "你的密码"); // 2. 建表(如果表已经存在可以注释掉这段,避免重复建表报错) String createSql = "CREATE TABLE IF NOT EXISTS jason " + "(ID INT NOT NULL," + "NAME json NOT NULL)"; pstmt = c.prepareStatement(createSql); pstmt.executeUpdate(); pstmt.close(); // 3. 准备JSON数据 String jsonStr = "{\"customer_name\": \"John\", \"items\": { \"description\": \"milk\", \"quantity\": 4 } }"; // 4. 用PreparedStatement做参数绑定插入 String insertSql = "INSERT INTO jason (ID, NAME) VALUES (?, ?::json)"; pstmt = c.prepareStatement(insertSql); pstmt.setInt(1, 1); // 绑定第一个参数ID pstmt.setString(2, jsonStr); // 绑定第二个参数JSON字符串,SQL侧显式转成json类型 int affectedRows = pstmt.executeUpdate(); System.out.println("插入成功,影响行数:" + affectedRows); c.commit(); // 提交事务 pstmt.close(); c.close(); } catch (Exception e) { e.printStackTrace(); // 出现异常回滚事务 try { if(c != null) c.rollback(); } catch (Exception rollbackE) { rollbackE.printStackTrace(); } } } }
额外注意事项
- 运行前确保项目已经引入PostgreSQL JDBC驱动,Maven依赖参考:
<dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>匹配你的PG服务版本</version> </dependency>
- 连接字符串里的库名、用户名、密码要替换成你自己的实际配置
内容的提问来源于stack exchange,提问作者Yushantha chathuranga
相关产品推荐
相关产品推荐

